package com.xbongbong.paas.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.xbongbong.callback.service.ApiCallBackService;
import com.xbongbong.crm.help.FineClueHelp;
import com.xbongbong.i18n.util.I18nMessageUtil;
import com.xbongbong.paas.constant.MessageConstant;
import com.xbongbong.paas.constant.PaasConstant;
import com.xbongbong.paas.domain.entity.CoverPaasMenuEntity;
import com.xbongbong.paas.domain.entity.PaasAppEntity;
import com.xbongbong.paas.domain.entity.PaasFormEntity;
import com.xbongbong.paas.domain.entity.PaasFormExplainEntity;
import com.xbongbong.paas.domain.entity.PaasMenuEntity;
import com.xbongbong.paas.domain.entity.ext.OptionalRangeEntity;
import com.xbongbong.paas.domain.entity.ext.PaasFormEntityExt;
import com.xbongbong.paas.domain.entity.ext.PaasMenuEntityExt;
import com.xbongbong.paas.domain.entity.ext.PaasProcessTemplateEntityExt;
import com.xbongbong.paas.enums.DelEnum;
import com.xbongbong.paas.enums.MenuTypeEnum;
import com.xbongbong.paas.enums.PlatFormEnum;
import com.xbongbong.paas.field.FieldAttrEntity;
import com.xbongbong.paas.help.CommonHelp;
import com.xbongbong.paas.help.PaasFormHelp;
import com.xbongbong.paas.help.SharePermissionHelp;
import com.xbongbong.paas.help.menu.InitDistributorMenuHelp;
import com.xbongbong.paas.help.menu.InitJxcMenuHelp;
import com.xbongbong.paas.help.menu.InitPriceMenuHelp;
import com.xbongbong.paas.help.menu.ProMenuHelp;
import com.xbongbong.paas.log.MongoLogHelp;
import com.xbongbong.paas.log.constant.LogMemoConstant;
import com.xbongbong.paas.model.CoverPaasMenuModel;
import com.xbongbong.paas.model.FineClueCompanyModel;
import com.xbongbong.paas.model.FineClueUserModel;
import com.xbongbong.paas.model.PaasAppModel;
import com.xbongbong.paas.model.PaasFormExplainModel;
import com.xbongbong.paas.model.PaasFormModel;
import com.xbongbong.paas.model.PaasMenuModel;
import com.xbongbong.paas.model.PaasProcessTemplateModel;
import com.xbongbong.paas.model.SearchCustomerCompanyModel;
import com.xbongbong.paas.model.SearchCustomerUserModel;
import com.xbongbong.paas.pojo.AccordConfigMenuPojo;
import com.xbongbong.paas.pojo.ApplicationSortPoJo;
import com.xbongbong.paas.pojo.ButtonPojo;
import com.xbongbong.paas.pojo.MenuSortPoJo;
import com.xbongbong.paas.pojo.dto.ApplicationCopyDTO;
import com.xbongbong.paas.pojo.dto.ApplicationSortDTO;
import com.xbongbong.paas.pojo.dto.CallCenterAccountUserInfoDTO;
import com.xbongbong.paas.pojo.dto.CallCenterModuleDTO;
import com.xbongbong.paas.pojo.dto.FormAddDTO;
import com.xbongbong.paas.pojo.dto.FormEntityAddDTO;
import com.xbongbong.paas.pojo.dto.FormExplainAddDTO;
import com.xbongbong.paas.pojo.dto.FormListInProcessDTO;
import com.xbongbong.paas.pojo.dto.MenuCopyDTO;
import com.xbongbong.paas.pojo.dto.MenuFormAddDTO;
import com.xbongbong.paas.pojo.dto.MenuFormDelDTO;
import com.xbongbong.paas.pojo.dto.MenuGroupAddDTO;
import com.xbongbong.paas.pojo.dto.MenuGroupDelDTO;
import com.xbongbong.paas.pojo.dto.MenuListDTO;
import com.xbongbong.paas.pojo.dto.MenuNameCheckDTO;
import com.xbongbong.paas.pojo.dto.MenuReportAddDTO;
import com.xbongbong.paas.pojo.dto.MenuReportDelDTO;
import com.xbongbong.paas.pojo.dto.MenuSortDTO;
import com.xbongbong.paas.pojo.dto.MenuUpdateDTO;
import com.xbongbong.paas.pojo.dto.MobileMenuListDTO;
import com.xbongbong.paas.pojo.dto.MobileProcessFormListDTO;
import com.xbongbong.paas.pojo.dto.ProcessFormListDTO;
import com.xbongbong.paas.pojo.dto.ProcessNodeTaskCountDTO;
import com.xbongbong.paas.pojo.dto.UserConfigAddDTO;
import com.xbongbong.paas.pojo.vo.AppProcessFormVO;
import com.xbongbong.paas.pojo.vo.CallCenterAccountUserInfoVO;
import com.xbongbong.paas.pojo.vo.CallCenterModuleVO;
import com.xbongbong.paas.pojo.vo.FormAddVO;
import com.xbongbong.paas.pojo.vo.FormExplainAddVO;
import com.xbongbong.paas.pojo.vo.FormListInProcessVO;
import com.xbongbong.paas.pojo.vo.IsActiveAIComboVO;
import com.xbongbong.paas.pojo.vo.IsActiveAliyunCallVO;
import com.xbongbong.paas.pojo.vo.MenuCopyVO;
import com.xbongbong.paas.pojo.vo.MenuFormAddVO;
import com.xbongbong.paas.pojo.vo.MenuFormDelVO;
import com.xbongbong.paas.pojo.vo.MenuGroupAddVO;
import com.xbongbong.paas.pojo.vo.MenuGroupDelVO;
import com.xbongbong.paas.pojo.vo.MenuListVO;
import com.xbongbong.paas.pojo.vo.MenuNameCheckVO;
import com.xbongbong.paas.pojo.vo.MenuReportAddVO;
import com.xbongbong.paas.pojo.vo.MenuReportDelVO;
import com.xbongbong.paas.pojo.vo.MenuSortVO;
import com.xbongbong.paas.pojo.vo.MenuUpdateVO;
import com.xbongbong.paas.pojo.vo.MobileMenuListVO;
import com.xbongbong.paas.pojo.vo.MobileProcessFormListVO;
import com.xbongbong.paas.pojo.vo.ProcessFormListVO;
import com.xbongbong.paas.pojo.vo.ProcessNodeTaskCountVO;
import com.xbongbong.paas.pojo.workflow.task.dto.WorkflowNodeTaskCountDTO;
import com.xbongbong.paas.pojo.workflow.task.vo.WorkflowNodeTaskCountVO;
import com.xbongbong.paas.redis.PaasRedisHelper;
import com.xbongbong.paas.redis.RedisConstant;
import com.xbongbong.paas.redis.RedisPrefixConstant;
import com.xbongbong.paas.service.CallCenterAccountService;
import com.xbongbong.paas.service.CallCenterCommonService;
import com.xbongbong.paas.service.CompanyConfigService;
import com.xbongbong.paas.service.DataConnectionService;
import com.xbongbong.paas.service.FeeLogService;
import com.xbongbong.paas.service.PaasAppService;
import com.xbongbong.paas.service.PaasFormExplainService;
import com.xbongbong.paas.service.PaasFormService;
import com.xbongbong.paas.service.PaasMenuService;
import com.xbongbong.paas.service.PaasProcessNodeTaskService;
import com.xbongbong.paas.service.PackageService;
import com.xbongbong.paas.service.ProMenuService;
import com.xbongbong.paas.service.SmartSettingsService;
import com.xbongbong.paas.service.UserConfigService;
import com.xbongbong.paas.service.WaterMarkService;
import com.xbongbong.paas.service.workflow.WorkflowApproveListPageOperationService;
import com.xbongbong.paas.toolbox.exception.XbbException;
import com.xbongbong.paas.toolbox.util.BeanUtil;
import com.xbongbong.paas.toolbox.util.CollectionsUtil;
import com.xbongbong.paas.toolbox.util.DateUtil;
import com.xbongbong.paas.toolbox.util.JsonHelperUtil;
import com.xbongbong.paas.toolbox.util.StringUtil;
import com.xbongbong.paas.toolbox.wrap.BaseDTO;
import com.xbongbong.paas.toolbox.wrap.UserVO;
import com.xbongbong.paas.toolbox.wrap.XbbResponse;
import com.xbongbong.pro.app.pojo.AppMenuFormIdPojo;
import com.xbongbong.pro.app.pojo.dto.AppMenuFormIdDTO;
import com.xbongbong.pro.app.pojo.vo.AppMenuFormIdVO;
import com.xbongbong.pro.companyconfig.pojo.dto.CompanyConfigAddBatchDTO;
import com.xbongbong.pro.companyconfig.pojo.dto.CompanyConfigAddDTO;
import com.xbongbong.pro.companyconfig.pojo.dto.CompanyConfigEnableDTO;
import com.xbongbong.pro.config.ProBaseConfig;
import com.xbongbong.pro.config.pojo.dto.UserConfigAddBatchDTO;
import com.xbongbong.pro.constant.I18nStringConstant;
import com.xbongbong.pro.constant.PackageConstant;
import com.xbongbong.pro.domain.entity.AppModuleEntity;
import com.xbongbong.pro.domain.entity.FineClueCompanyEntity;
import com.xbongbong.pro.domain.entity.FineClueUserEntity;
import com.xbongbong.pro.domain.entity.SearchCustomerCompanyEntity;
import com.xbongbong.pro.domain.entity.SearchCustomerUserEntity;
import com.xbongbong.pro.enums.AccessLinkEnum;
import com.xbongbong.pro.enums.ContractCompareFeeStatusEnum;
import com.xbongbong.pro.enums.DistributorMarkEnum;
import com.xbongbong.pro.enums.ErrorCodeEnum;
import com.xbongbong.pro.enums.FineClueEnum;
import com.xbongbong.pro.enums.HomeMenuEnum;
import com.xbongbong.pro.enums.PackageTypeEnum;
import com.xbongbong.pro.enums.SaasMarkEnum;
import com.xbongbong.pro.enums.SoukeMealEnum;
import com.xbongbong.pro.enums.ValueAddedTypeEnum;
import com.xbongbong.pro.enums.errorcodes.MarketingErrorCodeEnum;
import com.xbongbong.pro.enums.errorcodes.ProErrorCodeEnum;
import com.xbongbong.pro.enums.errorcodes.SystemErrorCodeEnum;
import com.xbongbong.pro.enums.errorcodes.TemplateCenterErrorCodeEnum;
import com.xbongbong.pro.enums.errorcodes.TemplateErrorCodeEnum;
import com.xbongbong.pro.enums.menu.enums.AICenterMenuEnum;
import com.xbongbong.pro.enums.menu.enums.CallCenterEnum;
import com.xbongbong.pro.enums.menu.enums.CallCenterMenuEnum;
import com.xbongbong.pro.enums.menu.enums.ContractCompareMenuEnum;
import com.xbongbong.pro.enums.menu.enums.ContractManegeCenterEnum;
import com.xbongbong.pro.enums.menu.enums.ControlCenterMenuEnum;
import com.xbongbong.pro.enums.menu.enums.CustomPageMenuEnum;
import com.xbongbong.pro.enums.menu.enums.EsignMenuEnum;
import com.xbongbong.pro.enums.menu.enums.FineClueMenuEnum;
import com.xbongbong.pro.enums.menu.enums.GroupMessageMenuEnum;
import com.xbongbong.pro.enums.menu.enums.OrganizationAuthorityEnum;
import com.xbongbong.pro.enums.menu.enums.OtherSetEnum;
import com.xbongbong.pro.enums.menu.enums.SearchCustomerMenuEnum;
import com.xbongbong.pro.enums.menu.enums.SystemAppMenuEnum;
import com.xbongbong.pro.enums.menu.enums.WorkOrderControlCenterEnum;
import com.xbongbong.pro.enums.menu.enums.WorkOrderMenuEnum;
import com.xbongbong.pro.enums.menu.enums.WorkOrderV2CenterEnum;
import com.xbongbong.pro.enums.packages.enums.FeaturesEnum;
import com.xbongbong.pro.enums.permission.enums.ProPermissionAliasEnum;
import com.xbongbong.pro.log.pojo.DetailLogPojo;
import com.xbongbong.pro.menu.pojo.MenuConfigPojo;
import com.xbongbong.pro.menu.pojo.MenuReturnPojo;
import com.xbongbong.pro.menu.pojo.dto.ControlCenterMenuListDTO;
import com.xbongbong.pro.menu.pojo.dto.ControlCenterMenuSetListDTO;
import com.xbongbong.pro.menu.pojo.dto.ControlCenterMenuSortDTO;
import com.xbongbong.pro.menu.pojo.dto.ControlMenuSetDTO;
import com.xbongbong.pro.menu.pojo.dto.HomeMenuSetListDTO;
import com.xbongbong.pro.menu.pojo.dto.MenuChangeStateDTO;
import com.xbongbong.pro.menu.pojo.dto.MenuFormAddBatchDTO;
import com.xbongbong.pro.menu.pojo.dto.MenuGroupAddBatchDTO;
import com.xbongbong.pro.menu.pojo.dto.MenuInitDTO;
import com.xbongbong.pro.menu.pojo.dto.MenuNewListDTO;
import com.xbongbong.pro.menu.pojo.dto.MenuQueryDTO;
import com.xbongbong.pro.menu.pojo.dto.MenuSetDTO;
import com.xbongbong.pro.menu.pojo.dto.MenuTopDTO;
import com.xbongbong.pro.menu.pojo.vo.AppMenuListVO;
import com.xbongbong.pro.menu.pojo.vo.ControlCenterMenuListVO;
import com.xbongbong.pro.menu.pojo.vo.ControlCenterMenuSetListVO;
import com.xbongbong.pro.menu.pojo.vo.ControlCenterMenuSortVO;
import com.xbongbong.pro.menu.pojo.vo.ControlCenterMenuVO;
import com.xbongbong.pro.menu.pojo.vo.ControlMenuSetVO;
import com.xbongbong.pro.menu.pojo.vo.HomeMenuSetListVO;
import com.xbongbong.pro.menu.pojo.vo.HomeMenuTopVO;
import com.xbongbong.pro.menu.pojo.vo.MenuChangeStateVO;
import com.xbongbong.pro.menu.pojo.vo.MenuFormAddBatchVO;
import com.xbongbong.pro.menu.pojo.vo.MenuGroupAddBatchVO;
import com.xbongbong.pro.menu.pojo.vo.MenuNewListVO;
import com.xbongbong.pro.menu.pojo.vo.MenuQueryVO;
import com.xbongbong.pro.menu.pojo.vo.MenuSetVO;
import com.xbongbong.pro.menu.pojo.vo.MenuTopVO;
import com.xbongbong.pro.menu.pojo.vo.PaasAppMenuVO;
import com.xbongbong.pro.message.feign.AIFeignClient;
import com.xbongbong.pro.message.pojo.dto.MessageCountDTO;
import com.xbongbong.pro.message.pojo.vo.MessageCountVO;
import com.xbongbong.pro.message.service.PushLinkService;
import com.xbongbong.pro.packageInfo.pojo.vo.BasePackageInfoVO;
import com.xbongbong.pro.service.toolbox.smartsettings.help.SmartSettingsHelp;
import com.xbongbong.saas.constant.BasicConstant;
import com.xbongbong.saas.constant.StringConstant;
import com.xbongbong.saas.domain.entity.WorkOrderFormEntity;
import com.xbongbong.saas.enums.CompanyConfigEnum;
import com.xbongbong.saas.enums.ListTopButtonEnum;
import com.xbongbong.saas.enums.OperateModuleTypeEnum;
import com.xbongbong.saas.enums.OperateTypeEnum;
import com.xbongbong.saas.enums.RedundantTemplateTypeEnum;
import com.xbongbong.saas.enums.SaasButtonEnum;
import com.xbongbong.saas.enums.XbbRefTypeEnum;
import com.xbongbong.saas.enums.business.CustomerManagementEnum;
import com.xbongbong.saas.help.MarketManagementBusinessHelp;
import com.xbongbong.saas.model.AppModuleModel;
import com.xbongbong.saas.model.WorkOrderFormModel;
import com.xbongbong.saas.service.StageInitService;
import com.xbongbong.saas.service.StockFlowBillService;
import com.xbongbong.saas.service.toolbox.help.LogHelp;
import com.xbongbong.saas.service.toolbox.help.UpdatePackageRedisService;
import com.xbongbong.sys.domain.entity.CompanyConfigEntity;
import com.xbongbong.sys.domain.entity.CompanyEntity;
import com.xbongbong.sys.domain.entity.UserConfigEntity;
import com.xbongbong.sys.enums.UserConfigEnum;
import com.xbongbong.sys.help.PackageHelp;
import com.xbongbong.sys.help.ProPermissionHelp;
import com.xbongbong.sys.model.CompanyConfigModel;
import com.xbongbong.sys.model.CompanyModel;
import com.xbongbong.sys.model.MirrorCompanyModel;
import com.xbongbong.sys.model.PriceSetModel;
import com.xbongbong.sys.model.UserConfigModel;
import com.xbongbong.util.ContractCompareUtil;
import org.apache.commons.collections4.CollectionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.i18n.LocaleContextHolder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.stream.Collectors;


/**
 * @author: wufeng
 * @date: 2018/8/8 10:36
 * @desrcption: 菜单实现类
 */
@Service("menuService")
public class PaasMenuServiceImpl implements PaasMenuService {

    private static final Logger LOG = LoggerFactory.getLogger(PaasMenuServiceImpl.class);
    /**
     * 表单名称的长度
     */
    private static final Integer FORM_NAME_LENGTH = 20;

    @Resource
    private PaasAppService paasAppService;
    @Resource
    private PaasFormService paasFormService;
    @Resource
    private UserConfigService userConfigService;
    @Resource
    private CompanyConfigService companyConfigService;
    @Resource
    private UpdatePackageRedisService updatePackageRedisService;
    @Resource
    private PaasMenuModel paasMenuModel;
    @Resource
    private PaasAppModel paasAppModel;
    @Resource
    private PaasFormModel paasFormModel;
    @Resource
    private UserConfigModel userConfigModel;
    @Resource
    private CompanyConfigModel companyConfigModel;
    @Resource
    private StageInitService stageInitService;
    @Resource
    private PaasFormExplainService paasFormExplainService;
    @Resource
    private PushLinkService pushLinkService;
    @Resource
    private PaasProcessNodeTaskService paasProcessNodeTaskService;
    @Resource
    private MongoLogHelp mongoLogHelp;
    @Resource
    private PaasProcessTemplateModel paasProcessTemplateModel;
    @Resource
    private WorkOrderFormModel workOrderFormModel;
    @Resource
    private LogHelp logHelp;
    @Resource
    private PaasFormHelp paasFormHelp;
    @Resource
    private ProMenuHelp proMenuHelp;
    @Resource
    private PaasRedisHelper paasRedisHelper;
    @Resource
    private MirrorCompanyModel mirrorCompanyModel;
    @Resource
    private PaasFormExplainModel paasFormExplainModel;
    @Resource
    private InitJxcMenuHelp initJxcMenuHelp;
    @Resource
    private CallCenterAccountService callCenterAccountService;
    @Resource
    private CallCenterCommonService callCenterCommonService;
    @Resource
    private SearchCustomerCompanyModel searchCustomerCompanyModel;
    @Resource
    private SearchCustomerUserModel searchCustomerUserModel;
    @Resource
    private SmartSettingsHelp smartSettingsHelp;
    @Resource
    private SmartSettingsService smartSettingsService;
    @Resource
    private AppModuleModel appModuleModel;
    @Resource
    private PackageHelp packageHelp;
    @Resource
    private MarketManagementBusinessHelp marketManagementBusinessHelp;
    @Resource
    private PackageService packageService;
    @Resource
    private InitDistributorMenuHelp initDistributorMenuHelp;
    @Resource
    private CommonHelp commonHelp;
    @Resource
    private WorkflowApproveListPageOperationService workflowApproveListPageOperationService;
    @Resource
    private DataConnectionService dataConnectionService;
    @Resource
    private InitPriceMenuHelp initPriceMenuHelp;
    @Resource
    private PriceSetModel priceSetModel;
    @Resource
    private StockFlowBillService stockFlowBillService;
    @Resource
    private FineClueCompanyModel fineClueCompanyModel;
    @Resource
    private FineClueUserModel fineClueUserModel;
    @Resource
    private ApiCallBackService apiCallBackService;
    @Resource
    private FineClueHelp fineClueHelp;
    @Resource
    private WaterMarkService waterMarkService;
    @Resource
    private CompanyModel companyModel;
    @Resource
    private CoverPaasMenuModel coverPaasMenuModel;
    @Resource
    private AIFeignClient aiFeignClient;
    @Resource
    private ProBaseConfig proBaseConfig;
    @Resource
    private ContractCompareUtil contractCompareUtil;
    @Resource
    private ProMenuService proMenuService;
    @Resource
    private FeeLogService feeLogService;
    @Resource
    private SharePermissionHelp sharePermissionHelp;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public MenuFormAddVO addFormMenu(MenuFormAddDTO menuFormAddDTO) throws XbbException {
        MenuFormAddVO menuFormAddVO = new MenuFormAddVO();
        PaasMenuEntity paasMenuEntity = new PaasMenuEntity();
        Integer saasMark = menuFormAddDTO.getSaasMark();
        Integer businessType = 0;
        if (StringUtil.isNotEmpty(menuFormAddDTO.getAlias())) {
            businessType = XbbRefTypeEnum.getByAlias(menuFormAddDTO.getAlias()).getCode();
        }
        if (Objects.equals(saasMark, SaasMarkEnum.SAAS.getCode())) {
            String alias = menuFormAddDTO.getAlias();
            RedundantTemplateTypeEnum templateTypeEnum = RedundantTemplateTypeEnum.getByAlias(alias);
            if (Objects.equals(templateTypeEnum.getCode(), RedundantTemplateTypeEnum.UNKNOWN.getCode())) {
                throw new XbbException(TemplateErrorCodeEnum.API_ERROR_350006);
            }
            //TODO haibin.zhang 取一下数据库是不是就做完了
            paasMenuEntity = paasMenuModel.getByAlias(alias, menuFormAddDTO.getAppId(), menuFormAddDTO.getCorpid());
        } else {
            String corpid = menuFormAddDTO.getCorpid();
            // 校验应用中表单和流程表单启用的数量
            validateFormMenuLengthInApp(corpid, menuFormAddDTO.getAppId());
            if (paasMenuEntity.getSort() == null) {
                PaasMenuEntity entity = new PaasMenuEntity();
                entity.setCorpid(paasMenuEntity.getCorpid());
                entity.setAppId(paasMenuEntity.getAppId());
                Map<String, Object> params = BeanUtil.convertBean2Map(menuFormAddDTO, true);
                params.put("orderByStr", "sort DESC ");
                Integer count = paasMenuModel.getEntitysCount(params);
                if (count == null) {
                    throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, MessageConstant.MENU_NOT_EXIST);
                }
                paasMenuEntity.setSort(count + 1);
            }
            paasMenuEntity.setUrl(AccessLinkEnum.PAAS_LIST.getUrl());
            BeanUtil.copyProperties(menuFormAddDTO, paasMenuEntity);
            paasMenuEntity.setCreatorId(menuFormAddDTO.getUserId());
            // 新建菜单表单
            paasMenuModel.insert(paasMenuEntity);
            // 记录日志
            String userName = menuFormAddDTO.getLoginUserName();
            String memo = String.format(I18nMessageUtil.getMessage(LogMemoConstant.LOG_MEMO_USER_ADD_MENU), userName, paasMenuEntity.getName());
            mongoLogHelp.buildLog(corpid, menuFormAddDTO.getUserId(), userName, OperateModuleTypeEnum.PAAS_MENU, OperateTypeEnum.NEW, paasMenuEntity.getId().toString(), paasMenuEntity.getName(), memo, menuFormAddDTO.getHttpHeader());
        }
        try {
            menuFormAddVO.setMenuId(paasMenuEntity.getId());
            // 生成菜单时，处理表单主表业务逻辑
            FormAddDTO formAddDTO = new FormAddDTO();
            BeanUtil.copyProperties(menuFormAddDTO, formAddDTO);
            formAddDTO.setMenuId(paasMenuEntity.getId());
            FormEntityAddDTO formEntityAddDTO = new FormEntityAddDTO();
            formEntityAddDTO.setSaasMark(saasMark);
            formEntityAddDTO.setBusinessType(businessType);
            formAddDTO.setFormAttr(formEntityAddDTO);
            FormAddVO formAddVO = paasFormService.add(formAddDTO);
            if (Objects.isNull(formAddVO)) {
                throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, MessageConstant.FORM_ADD_FAILED);
            }
            Long formId = formAddVO.getFormId();
            menuFormAddVO.setFormId(formId);
            menuFormAddVO.setBusinessType(businessType);
            menuFormAddVO.setSaasMark(saasMark);
            // 字段信息添加
            FormExplainAddDTO formExplainAddDTO = new FormExplainAddDTO();
            BeanUtil.copyProperties(menuFormAddDTO, formExplainAddDTO);
            formExplainAddDTO.setMenuId(paasMenuEntity.getId());
            formExplainAddDTO.setFormId(formId);
            formExplainAddDTO.setSaasMark(saasMark);
            formExplainAddDTO.setBusinessType(businessType);
            FormExplainAddVO formExplainAddVO = paasFormExplainService.add(formExplainAddDTO);
            if (Objects.isNull(formExplainAddVO)) {
                throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, MessageConstant.FORM_EXPLAIN_ADD_FAILED);
            }
            menuFormAddVO.setFormExplainId(formExplainAddVO.getFormExplainId());

            // 客户、机会、线索新建表单的时候需要初始化阶段
            boolean needInitStage = Objects.equals(XbbRefTypeEnum.CUSTOMER_MANAGEMENT.getCode(), businessType) ||
                    Objects.equals(XbbRefTypeEnum.SALES_OPPORTUNITY.getCode(), businessType) ||
                    Objects.equals(XbbRefTypeEnum.CLUE.getCode(), businessType);
            if (needInitStage) {
                stageInitService.init(menuFormAddDTO.getCorpid(), businessType, formId);
            }
        } catch (XbbException e) {
            throw e;
        } catch (Exception e) {
            LOG.error("menu数据库插入菜单出错", e);
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, SystemErrorCodeEnum.API_ERROR_100001.getMsg());
        }

        return menuFormAddVO;
    }

    @Override
    public MenuNameCheckVO checkTemplateName(MenuNameCheckDTO menuNameCheckDTO) throws XbbException {
        MenuNameCheckVO menuNameCheckVO = new MenuNameCheckVO();
        Map<String, Object> params = BeanUtil.convertBean2Map(menuNameCheckDTO, true);
        params.put("del", DelEnum.NORMAL.getDel());
        Integer count = paasFormModel.getEntitysCount(params);
        if (count > 0) {
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, MessageConstant.MENU_NAME_EXIST);
        }
        return menuNameCheckVO;
    }

    @Override
    public MenuFormAddBatchVO addBatchFormMenu(MenuFormAddBatchDTO menuFormAddBatchDTO) throws XbbException {
        return proMenuService.addBatchFormMenu(menuFormAddBatchDTO);
    }

    @Override
    public MenuGroupAddBatchVO addBatchGroupMenu(MenuGroupAddBatchDTO menuGroupAddBatchDTO) throws XbbException {
        return proMenuService.addBatchGroupMenu(menuGroupAddBatchDTO);
    }

    @Override
    public MenuGroupAddVO addMenu(MenuGroupAddDTO menuGroupAddDTO) throws XbbException {
        PaasMenuEntity paasMenuEntity = new PaasMenuEntity();
        BeanUtil.copyProperties(menuGroupAddDTO, paasMenuEntity);
        paasMenuEntity.setCreatorId(menuGroupAddDTO.getUserId());
        String corpid = menuGroupAddDTO.getCorpid();

        try {
            if (paasMenuEntity.getSort() == null) {
                Integer count = getCount(BeanUtil.convertBean2Map(menuGroupAddDTO, true));
                paasMenuEntity.setSort(count + 1);
            }
            paasMenuEntity.setDistributorMark(DistributorMarkEnum.OTHER.getCode());
            paasMenuModel.insert(paasMenuEntity);
            String userName = menuGroupAddDTO.getLoginUserName();
            // 记录日志
            String memo = String.format(I18nMessageUtil.getMessage(LogMemoConstant.LOG_MEMO_USER_ADD_MENU), userName, paasMenuEntity.getName());
            mongoLogHelp.buildLog(corpid, menuGroupAddDTO.getUserId(), userName, OperateModuleTypeEnum.PAAS_MENU, OperateTypeEnum.NEW, menuGroupAddDTO.getAppId().toString(), "", memo, menuGroupAddDTO.getHttpHeader());

        } catch (XbbException e) {
            throw e;
        } catch (Exception e) {
            LOG.error("menu数据库插入出错", e);
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, SystemErrorCodeEnum.API_ERROR_100001.getMsg());
        }
        MenuGroupAddVO menuGroupAddVO = new MenuGroupAddVO();
        menuGroupAddVO.setMenuId(paasMenuEntity.getId());
        return menuGroupAddVO;
    }

    @Override
    public MenuReportAddVO addReportMenu(MenuReportAddDTO menuReportAddDTO) throws XbbException {
        PaasMenuEntity paasMenuEntity = new PaasMenuEntity();
        BeanUtil.copyProperties(menuReportAddDTO, paasMenuEntity);
        paasMenuEntity.setCreatorId(menuReportAddDTO.getUserId());
        try {
            String corpid = menuReportAddDTO.getCorpid();
            if (paasMenuEntity.getSort() == null) {
                Integer count = getCount(BeanUtil.convertBean2Map(menuReportAddDTO, true));
                paasMenuEntity.setSort(count + 1);
            }
            paasMenuModel.insert(paasMenuEntity);
            String userName = menuReportAddDTO.getLoginUserName();
            // 记录日志
            String memo = String.format(I18nMessageUtil.getMessage(LogMemoConstant.LOG_MEMO_USER_ADD_MENU), userName, paasMenuEntity.getName());
            mongoLogHelp.buildLog(corpid, menuReportAddDTO.getUserId(), userName, OperateModuleTypeEnum.PAAS_MENU, OperateTypeEnum.NEW, menuReportAddDTO.getAppId().toString(), "", memo, menuReportAddDTO.getHttpHeader());

        } catch (XbbException e) {
            throw e;
        } catch (Exception e) {
            LOG.error("menu数据库插入出错", e);
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, SystemErrorCodeEnum.API_ERROR_100001.getMsg());
        }
        MenuReportAddVO menuReportAddVO = new MenuReportAddVO();
        menuReportAddVO.setMenuId(paasMenuEntity.getId());
        return menuReportAddVO;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public MenuUpdateVO updateMenu(MenuUpdateDTO menuUpdateDTO) throws XbbException {
        PaasMenuEntity paasMenuEntity = new PaasMenuEntity();
        BeanUtil.copyProperties(menuUpdateDTO, paasMenuEntity, false);
        try {
            PaasMenuEntity entity = paasMenuModel.getByKey(menuUpdateDTO.getMenuId(), menuUpdateDTO.getCorpid());
            if (entity == null) {
                throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, MessageConstant.MENU_NOT_EXIST);
            }
            String message = validateName(entity, menuUpdateDTO);
            if (StringUtil.isNotEmpty(message)) {
                throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, message);
            }
            paasMenuEntity.setId(menuUpdateDTO.getMenuId());
            paasMenuModel.update(paasMenuEntity);
            String corpid = menuUpdateDTO.getCorpid();
            // 记录日志
            String userName = menuUpdateDTO.getLoginUserName();
            String memo = String.format(I18nMessageUtil.getMessage(LogMemoConstant.LOG_MEMO_USER_UPDATE_MENU), userName, paasMenuEntity.getName());
            JSONObject oldObj = JsonHelperUtil.parseObject(JSONObject.toJSONString(entity));
            JSONObject newObj = JsonHelperUtil.parseObject(JSONObject.toJSONString(paasMenuEntity));
            List<DetailLogPojo> detailArr = logHelp.getDetailArr4Normal(corpid, OperateModuleTypeEnum.PAAS_MENU, oldObj, newObj);
            mongoLogHelp.buildLog4DetailArr(detailArr, corpid, menuUpdateDTO.getUserId(), userName, OperateModuleTypeEnum.PAAS_MENU, OperateTypeEnum.EDIT, menuUpdateDTO.getMenuId().toString(), paasMenuEntity.getName(), memo, menuUpdateDTO.getHttpHeader());

            // 更新表单名称
            Integer type = entity.getType();
            if (MenuTypeEnum.FORM.getType().equals(type) || MenuTypeEnum.PROCESS_FORM.getType().equals(type)) {
                Map<String, Object> param = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
                param.put(StringConstant.CORPID, corpid);
                param.put(StringConstant.DEL, DelEnum.NORMAL.getDel());
                param.put("menuId", menuUpdateDTO.getMenuId());
                List<PaasFormEntityExt> formList = paasFormModel.list(param);
                if (Objects.isNull(formList)) {
                    throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, MessageConstant.FORM_NOT_EXIST);
                }
                if (formList.size() == 1) {
                    PaasFormEntityExt oldPaasFormEntity = formList.get(0);
                    String oldName = oldPaasFormEntity.getName();
                    String name = menuUpdateDTO.getName();
                    PaasFormEntity paasFormEntity = new PaasFormEntity();
                    paasFormEntity.setCorpid(menuUpdateDTO.getCorpid());
                    paasFormEntity.setMenuId(menuUpdateDTO.getMenuId());
                    paasFormEntity.setId(oldPaasFormEntity.getId());
                    paasFormEntity.setName(name);
                    paasFormEntity.setNameEn(menuUpdateDTO.getNameEn());
                    paasFormModel.updateName(paasFormEntity);
                    // 记录日志
                    memo = String.format(I18nMessageUtil.getMessage(LogMemoConstant.LOG_MEMO_USER_UPDATE_FORM_NAME), userName, oldName, name);
                    mongoLogHelp.buildLog(corpid, menuUpdateDTO.getUserId(), userName, OperateModuleTypeEnum.PAAS_FORM, OperateTypeEnum.EDIT, paasFormEntity.getId().toString(), name, memo, menuUpdateDTO.getHttpHeader());
                }
            }
        } catch (XbbException e) {
            throw e;
        } catch (Exception e) {
            LOG.error("menu数据库更新出错", e);
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, SystemErrorCodeEnum.API_ERROR_100001.getMsg());
        }
        MenuUpdateVO menuUpdateVO = new MenuUpdateVO();
        menuUpdateVO.setMenuId(paasMenuEntity.getId());
        return menuUpdateVO;
    }

    /**
     * 因为更新表单名称和样式都是一个接口，所以需要加个方法判断
     *
     * @param entity
     * @param menuUpdateDTO
     * @return
     */
    private String validateName(PaasMenuEntity entity, MenuUpdateDTO menuUpdateDTO) {
        String message = "";
        String name = MenuTypeEnum.getName(entity.getType());
        if (entity.getType().equals(MenuTypeEnum.FORM.getType()) || entity.getType().equals(MenuTypeEnum.PROCESS_FORM.getType())) {
            name = "表单";
        }
        if (menuUpdateDTO.getName() == null) {
            message = "请输入" + name + "名称";
        } else if (StringUtil.isEmpty(menuUpdateDTO.getName())) {
            message = name + "名称不能为空";
        }
        return message;
    }

    @Override
    public MenuGroupDelVO deleteMenu(MenuGroupDelDTO menuGroupDelDTO) throws XbbException {
        PaasMenuEntity paasMenuEntity = new PaasMenuEntity();
        BeanUtil.copyProperties(menuGroupDelDTO, paasMenuEntity);
        try {
            String corpid = menuGroupDelDTO.getCorpid();
            // 需要查看分组下是否有数据
            Map<String, Object> map = BeanUtil.convertBean2Map(menuGroupDelDTO);
            map.put("parentId", menuGroupDelDTO.getMenuId());
            map.put("orderByStr", "sort");
            map.put(StringConstant.DEL, DelEnum.NORMAL.getDel());
            List<PaasMenuEntity> list = paasMenuModel.list(map);
            if (list == null) {
                throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, MessageConstant.MENU_NOT_EXIST);
            }
            // 当分组下有数据时，不能删除
            if (list.size() > 0) {
                throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, MessageConstant.MENU_HAS_DATA);
            }
            PaasMenuEntity entity = paasMenuModel.getByKey(menuGroupDelDTO.getMenuId(), corpid);
            if (entity == null) {
                throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, MessageConstant.MENU_NOT_EXIST);
            }
            // 删除分组
            paasMenuModel.delete(menuGroupDelDTO.getMenuId(), corpid);
            // 记录日志
            String userName = menuGroupDelDTO.getLoginUserName();
            String memo = String.format(I18nMessageUtil.getMessage(LogMemoConstant.LOG_MEMO_USER_DELETE_MENU), userName, paasMenuEntity.getName());
            mongoLogHelp.buildLog(corpid, menuGroupDelDTO.getUserId(), userName, OperateModuleTypeEnum.PAAS_MENU, OperateTypeEnum.DELETE, menuGroupDelDTO.getMenuId().toString(), entity.getName(), memo, menuGroupDelDTO.getHttpHeader());

        } catch (XbbException e) {
            throw e;
        } catch (Exception e) {
            LOG.error("menu数据库删除出错", e);
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, SystemErrorCodeEnum.API_ERROR_100001.getMsg());
        }
        MenuGroupDelVO menuGroupDelVO = new MenuGroupDelVO();
        menuGroupDelVO.setMenuId(paasMenuEntity.getId());
        return menuGroupDelVO;
    }

    @Override
    public MenuFormDelVO deleteFormMenu(MenuFormDelDTO menuFormDelDTO) throws XbbException {
        PaasMenuEntity paasMenuEntity = new PaasMenuEntity();
        BeanUtil.copyProperties(menuFormDelDTO, paasMenuEntity);
        try {
            String corpid = menuFormDelDTO.getCorpid();
            PaasMenuEntity menuEntity = paasMenuModel.getByKey(menuFormDelDTO.getMenuId(), corpid);
            if (menuEntity == null) {
                throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, MessageConstant.MENU_NOT_EXIST);
            }
            if (Objects.equals(SaasMarkEnum.SAAS.getCode(), menuEntity.getSaasMark())) {
                throw new XbbException(ProErrorCodeEnum.API_ERROR_500016, ProErrorCodeEnum.API_ERROR_500016.getMsg());
            }
            String userName = menuFormDelDTO.getLoginUserName();
            // 删除菜单
            paasMenuModel.delete(menuEntity.getId(), corpid);
            // 记录日志

            String memo = String.format(I18nMessageUtil.getMessage(LogMemoConstant.LOG_MEMO_USER_DELETE_MENU), userName, menuEntity.getName());
            mongoLogHelp.buildLog(corpid, menuFormDelDTO.getUserId(), userName, OperateModuleTypeEnum.PAAS_MENU, OperateTypeEnum.DELETE, menuFormDelDTO.getMenuId().toString(), menuEntity.getName(), memo, menuFormDelDTO.getHttpHeader());

        } catch (XbbException e) {
            throw e;
        } catch (Exception e) {
            LOG.error("menu数据库删除出错", e);
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, SystemErrorCodeEnum.API_ERROR_100001.getMsg());
        }
        MenuFormDelVO menuFormDelVO = new MenuFormDelVO();
        menuFormDelVO.setMenuId(paasMenuEntity.getId());
        return menuFormDelVO;
    }

    @Override
    public MenuReportDelVO deleteReportMenu(MenuReportDelDTO menuReportDelDTO) throws XbbException {
        PaasMenuEntity paasMenuEntity = new PaasMenuEntity();
        BeanUtil.copyProperties(menuReportDelDTO, paasMenuEntity);
        String corpid = menuReportDelDTO.getCorpid();
        try {
            //TODO 需要查看报表下是否有数据
            PaasMenuEntity entity = paasMenuModel.getByKey(menuReportDelDTO.getMenuId(), corpid);
            if (entity == null) {
                throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, MessageConstant.MENU_NOT_EXIST);
            }
            // 删除分组
            paasMenuModel.delete(menuReportDelDTO.getMenuId(), corpid);

            // 记录日志
            String userName = menuReportDelDTO.getLoginUserName();
            String memo = String.format(I18nMessageUtil.getMessage(LogMemoConstant.LOG_MEMO_USER_DELETE_MENU), userName, paasMenuEntity.getName());
            mongoLogHelp.buildLog(corpid, menuReportDelDTO.getUserId(), userName, OperateModuleTypeEnum.PAAS_MENU, OperateTypeEnum.DELETE, menuReportDelDTO.getMenuId().toString(), entity.getName(), memo, menuReportDelDTO.getHttpHeader());

        } catch (XbbException e) {
            throw e;
        } catch (Exception e) {
            LOG.error("menu数据库删除出错", e);
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, SystemErrorCodeEnum.API_ERROR_100001.getMsg());
        }
        MenuReportDelVO menuReportDelVO = new MenuReportDelVO();
        menuReportDelVO.setMenuId(paasMenuEntity.getId());
        return menuReportDelVO;
    }

    @Override
    public MenuListVO listMenu(MenuListDTO menuListDTO) throws XbbException {
        MenuListVO menuListVO = new MenuListVO();
        try {
            Map<String, Object> map = BeanUtil.convertBean2Map(menuListDTO);
            map.put("id", menuListDTO.getAppId());
            map.put("orderByStr", "sort");
            List<PaasAppEntity> paasAppEntityList = paasAppModel.list(map);
            if (paasAppEntityList == null) {
                throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, MessageConstant.APP_NOT_EXIST);
            }
            menuListVO.setPaasAppEntityList(paasAppEntityList);

            List<PaasMenuEntityExt> menuList = paasMenuModel.getMenuList(map);
            if (menuList == null) {
                throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, MessageConstant.MENU_NOT_EXIST);
            }
            menuListVO.setMenuList(menuList);
        } catch (XbbException e) {
            throw e;
        } catch (Exception e) {
            LOG.error("paasApp数据库查询出错", e);
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, SystemErrorCodeEnum.API_ERROR_100001.getMsg());
        }
        return menuListVO;
    }

    @Override
    public MenuSortVO sortMenu(MenuSortDTO menuSortDTO) throws XbbException {
        List<PaasMenuEntity> paasMenuEntityList = new ArrayList<>();

        try {
            String corpid = menuSortDTO.getCorpid();
            List<Long> idsList = new ArrayList<>();
            for (MenuSortPoJo menuSortPoJo : menuSortDTO.getMenuList()) {
                PaasMenuEntity paasMenuEntity = new PaasMenuEntity();
                long now = DateUtil.getInt();
                Long id = menuSortPoJo.getId();
                Integer sort = menuSortPoJo.getSort();
                Long parentId = menuSortPoJo.getParentId();
                if (id == null || sort == null || parentId == null) {
                    throw new XbbException(SystemErrorCodeEnum.API_ERROR_100002, SystemErrorCodeEnum.API_ERROR_100002.getMsg());
                }
                paasMenuEntity.setId(id);
                paasMenuEntity.setSort(sort);
                paasMenuEntity.setParentId(parentId);
                paasMenuEntity.setUpdateTime(now);
                paasMenuEntityList.add(paasMenuEntity);
                idsList.add(id);
            }
            Map<String, Object> params = BeanUtil.convertBean2Map(menuSortDTO, true);
            params.put("idIn", idsList);
            List<PaasMenuEntity> menuList = paasMenuModel.list(params);
            if (menuList == null || menuList.size() != paasMenuEntityList.size()) {
                throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, MessageConstant.MENU_NOT_EXIST);
            }
            paasMenuModel.updateSort(paasMenuEntityList, menuSortDTO.getCorpid());
            // 记录日志
            String userName = menuSortDTO.getLoginUserName();
            String memo = String.format(I18nMessageUtil.getMessage(LogMemoConstant.LOG_MEMO_USER_UPDATE_MENU_SORT), userName, "");
            mongoLogHelp.buildLog(corpid, menuSortDTO.getUserId(), userName, OperateModuleTypeEnum.PAAS_MENU, OperateTypeEnum.EDIT, "", "", memo, menuSortDTO.getHttpHeader());

        } catch (XbbException e) {
            throw e;
        } catch (Exception e) {
            LOG.error("menu数据库更新出错", e);
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, SystemErrorCodeEnum.API_ERROR_100001.getMsg());
        }
        MenuSortVO menuSortVO = new MenuSortVO();
        menuSortVO.setMenuList(menuSortDTO.getMenuList());
        return menuSortVO;
    }

    @Override
    public ProcessFormListVO getProcessFormList(ProcessFormListDTO processFormListDTO) throws XbbException {
        ProcessFormListVO processFormListVO = new ProcessFormListVO();
        try {
            String corpid = processFormListDTO.getCorpid();
            Map<String, Object> map = BeanUtil.convertBean2Map(processFormListDTO, true);
            map.put("enable", 1);
            map.put("orderByStr", "sort");
            List<PaasAppEntity> appList = paasAppModel.list(map);
            if (appList == null) {
                throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, MessageConstant.APP_NOT_EXIST);
            }
            Map<Long, PaasAppEntity> appMap = new HashMap<>(appList.size());
            appList.forEach(item -> {
                appMap.put(item.getId(), item);
            });
            Integer formNum = updatePackageRedisService.getUnusedNumPackageLimit(corpid, ValueAddedTypeEnum.CUSTOM_FORM_NUM);
            Integer appNum = updatePackageRedisService.getUnusedNumPackageLimit(corpid, ValueAddedTypeEnum.CUSTOM_FORM_NUM);
            map = BeanUtil.convertBean2Map(processFormListDTO, true);
            map.put("enable", 1);
            List<PaasProcessTemplateEntityExt> processTemplateList = paasProcessTemplateModel.list(map);
            if (processTemplateList == null) {
                throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, MessageConstant.PROCESS_NOT_EXIST);
            }
            Map<Long, PaasProcessTemplateEntityExt> processTemplateMap = new HashMap<>(processTemplateList.size());
            Map<Long, PaasProcessTemplateEntityExt> processWorkOrderTemplateMap = new HashMap<>(processTemplateList.size());
            processTemplateList.forEach((item) -> {
                if (Objects.equals(item.getBusinessType(), XbbRefTypeEnum.WORK_ORDER.getCode())) {
                    processWorkOrderTemplateMap.put(item.getFormId(), item);
                } else {
                    processTemplateMap.put(item.getFormId(), item);
                }
            });
            map = BeanUtil.convertBean2Map(processFormListDTO, true);
            map.put("is_process_form", 1);
            map.put("enable", 1);
            List<WorkOrderFormEntity> workOrderFormEntityList = workOrderFormModel.findEntitys(map);
            List<PaasFormEntityExt> paasFormEntityExtList = paasFormModel.list(map);
            boolean isAdmin = processFormListDTO.getLoginUser().isAdmin();
            Map<Long, List<PaasFormEntityExt>> formMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
            for (PaasFormEntityExt paasFormEntityExt : paasFormEntityExtList) {
                Integer businessType = paasFormEntityExt.getBusinessType();
                PaasProcessTemplateEntityExt paasProcessTemplateEntityExt = processTemplateMap.get(paasFormEntityExt.getId());
                if (paasProcessTemplateEntityExt == null || paasProcessTemplateEntityExt.getEnable().equals(0)) {
                    continue;
                }
                if (Objects.equals(businessType, XbbRefTypeEnum.CUSTOMER_MANAGEMENT.getCode()) || Objects.equals(businessType, XbbRefTypeEnum.CONTRACT.getCode())) {
                    List<OptionalRangeEntity> permissions = JSON.parseArray(paasFormEntityExt.getPermission(), OptionalRangeEntity.class);
                    if (permissions != null && !permissions.isEmpty() && paasFormHelp.haveNoPermission(processFormListDTO.getLoginUser(), permissions)) {
                        continue;
                    }
                }
                if (Objects.equals(SaasMarkEnum.PAAS.getCode(), paasFormEntityExt.getSaasMark())) {
                    if (formNum > 0 || appNum > 0) {
                        paasFormEntityExt.setMessage(String.format(I18nMessageUtil.getMessage(PackageConstant.CUSTOM_FORM_SIZE_MESSAGE), formNum));
                        if (appNum > 0) {
                            paasFormEntityExt.setMessage(I18nMessageUtil.getMessage(PackageConstant.FORM_PACKAGE_LIMIT_MESSAGE));
                        }
                        if (isAdmin) {
                            paasFormEntityExt.setUpgrade(1);
                        }
                        paasFormEntityExt.setPackageLimit(1);
                    }
                }

                if (formMap.containsKey(paasFormEntityExt.getAppId())) {
                    List<PaasFormEntityExt> formList = formMap.get(paasFormEntityExt.getAppId());
                    formList.add(paasFormEntityExt);
                    formMap.put(paasFormEntityExt.getAppId(), formList);
                } else {
                    List<PaasFormEntityExt> formList = new ArrayList<>();
                    formList.add(paasFormEntityExt);
                    formMap.put(paasFormEntityExt.getAppId(), formList);
                }
            }
            for (WorkOrderFormEntity workOrderFormEntity : workOrderFormEntityList) {
                PaasProcessTemplateEntityExt paasProcessTemplateEntityExt = processWorkOrderTemplateMap.get(workOrderFormEntity.getId());
                if (paasProcessTemplateEntityExt == null || paasProcessTemplateEntityExt.getEnable().equals(0)) {
                    continue;
                }
                PaasFormEntityExt paasFormEntityExt = new PaasFormEntityExt();
                BeanUtil.copyProperties(workOrderFormEntity, paasFormEntityExt);
                paasFormEntityExt.setSaasMark(SaasMarkEnum.SAAS.getCode());
                paasFormEntityExt.setBusinessType(XbbRefTypeEnum.WORK_ORDER.getCode());
                if (formMap.containsKey(workOrderFormEntity.getAppId())) {
                    List<PaasFormEntityExt> formList = formMap.get(workOrderFormEntity.getAppId());
                    formList.add(paasFormEntityExt);
                    formMap.put(workOrderFormEntity.getAppId(), formList);
                } else {
                    List<PaasFormEntityExt> formList = new ArrayList<>();
                    formList.add(paasFormEntityExt);
                    formMap.put(paasFormEntityExt.getAppId(), formList);
                }
            }
            List<AppProcessFormVO> processFormList = new ArrayList<>();
            appList.forEach((item) -> {
                AppProcessFormVO appProcessFormVO = new AppProcessFormVO();
                BeanUtil.copyProperties(item, appProcessFormVO);
                appProcessFormVO.setFormList(formMap.get(item.getId()));
                processFormList.add(appProcessFormVO);
            });

            processFormListVO.setProcessFormList(processFormList);
        } catch (XbbException e) {
            throw e;
        } catch (Exception e) {
            LOG.error("menu数据库检索当前公司的应用下可用的流程表单出错", e);
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, SystemErrorCodeEnum.API_ERROR_100001.getMsg());
        }
        return processFormListVO;
    }

    @Override
    public MobileProcessFormListVO getMobileProcessFormList(MobileProcessFormListDTO processFormListDTO) throws XbbException {
        MobileProcessFormListVO processFormListVO = new MobileProcessFormListVO();
        try {
            Map<String, Object> map = BeanUtil.convertBean2Map(processFormListDTO);
            List<PaasMenuEntityExt> paasMenuEntityExtList = paasMenuModel.getSomeAppProcessFormList(map);
            if (paasMenuEntityExtList == null) {
                throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, SystemErrorCodeEnum.API_ERROR_100001.getMsg());
            }
            map = BeanUtil.convertBean2Map(processFormListDTO);
            List<PaasProcessTemplateEntityExt> processTemplateList = paasProcessTemplateModel.list(map);
            if (processTemplateList == null) {
                throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, MessageConstant.PROCESS_NOT_EXIST);
            }
            Map<Long, PaasProcessTemplateEntityExt> processTemplateMap = new HashMap<>(processTemplateList.size());
            processTemplateList.forEach((item) -> {
                processTemplateMap.put(item.getMenuId(), item);
            });
            List<PaasMenuEntityExt> list = new ArrayList<>();
            List<PaasMenuEntity> menuList = new ArrayList<>();
            for (PaasMenuEntityExt paasMenuEntityExt : paasMenuEntityExtList) {

                if (paasMenuEntityExt.getProcessFormList().isEmpty() && paasMenuEntityExt.getType().equals(MenuTypeEnum.PROCESS_FORM.getType())) {
                    PaasProcessTemplateEntityExt paasProcessTemplateEntityExt = processTemplateMap.get(paasMenuEntityExt.getId());
                    if (paasProcessTemplateEntityExt == null || paasProcessTemplateEntityExt.getEnable().equals(0)) {
                        continue;
                    }
                    PaasMenuEntity paasMenuEntity = new PaasMenuEntity();
                    BeanUtil.copyProperties(paasMenuEntityExt, paasMenuEntity);
                    menuList.add(paasMenuEntity);
                } else if (!paasMenuEntityExt.getProcessFormList().isEmpty()) {
                    List<PaasMenuEntity> processFormList = new ArrayList<>();
                    for (PaasMenuEntity item : paasMenuEntityExt.getProcessFormList()) {
                        PaasProcessTemplateEntityExt paasProcessTemplateEntityExt = processTemplateMap.get(item.getId());
                        if (paasProcessTemplateEntityExt == null || paasProcessTemplateEntityExt.getEnable().equals(0)) {
                            continue;
                        }
                        processFormList.add(item);
                    }
                    if (!processFormList.isEmpty()) {
                        paasMenuEntityExt.setProcessFormList(processFormList);
                        list.add(paasMenuEntityExt);
                    }
                }
            }
            if (!menuList.isEmpty()) {
                PaasMenuEntityExt paasMenuEntityExt = new PaasMenuEntityExt();
                paasMenuEntityExt.setName("其他");
                paasMenuEntityExt.setProcessFormList(menuList);
                list.add(paasMenuEntityExt);
            }
            processFormListVO.setProcessFormList(list);
        } catch (XbbException e) {
            throw e;
        } catch (Exception e) {
            LOG.error("menu数据库检索当前公司的应用下可用的流程表单出错", e);
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, SystemErrorCodeEnum.API_ERROR_100001.getMsg());
        }
        return processFormListVO;
    }

    @Override
    public MobileMenuListVO mobileMenuList(MobileMenuListDTO mobileMenuListDTO) throws XbbException {
        MobileMenuListVO mobileMenuListVO = new MobileMenuListVO();
        try {
            PaasAppEntity paasAppEntityList = paasAppModel.getByKey(mobileMenuListDTO.getAppId(), mobileMenuListDTO.getCorpid());
            if (paasAppEntityList == null) {
                throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, MessageConstant.APP_NOT_EXIST);
            }
            mobileMenuListVO.setPaasAppEntity(paasAppEntityList);

            Map<String, Object> map = BeanUtil.convertBean2Map(mobileMenuListDTO);
            List<PaasMenuEntityExt> menuList = paasMenuModel.getMenuList(map);
            if (menuList == null) {
                throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, MessageConstant.MENU_NOT_EXIST);
            }

            List<PaasMenuEntityExt> list = new ArrayList<>();
            List<PaasMenuEntity> otherMenuList = new ArrayList<>();
            for (PaasMenuEntityExt paasMenuEntityExt : menuList) {
                if (paasMenuEntityExt.getSubMenuList().isEmpty() && !paasMenuEntityExt.getType().equals(MenuTypeEnum.GROUP.getType())) {
                    PaasMenuEntity paasMenuEntity = new PaasMenuEntity();
                    BeanUtil.copyProperties(paasMenuEntityExt, paasMenuEntity);
                    otherMenuList.add(paasMenuEntity);
                } else if (!paasMenuEntityExt.getSubMenuList().isEmpty()) {
                    list.add(paasMenuEntityExt);
                }
            }
            if (!menuList.isEmpty()) {
                PaasMenuEntityExt paasMenuEntityExt = new PaasMenuEntityExt();
                paasMenuEntityExt.setName("其他");
                paasMenuEntityExt.setSubMenuList(otherMenuList);
                list.add(paasMenuEntityExt);
            }
            mobileMenuListVO.setMenuList(list);
        } catch (XbbException e) {
            throw e;
        } catch (Exception e) {
            LOG.error("menu数据库手机端检索菜单出错", e);
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, SystemErrorCodeEnum.API_ERROR_100001.getMsg());
        }
        return mobileMenuListVO;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public MenuCopyVO copy(MenuCopyDTO menuCopyDTO) throws XbbException {
        MenuCopyVO menuCopyVO = new MenuCopyVO();
        try {
            String corpid = menuCopyDTO.getCorpid();
            PaasMenuEntity paasMenuEntity = paasMenuModel.getByKey(menuCopyDTO.getMenuId(), corpid);
            if (paasMenuEntity == null) {
                throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, MessageConstant.MENU_NOT_EXIST);
            }
            if (SaasMarkEnum.SAAS.getCode().equals(paasMenuEntity.getSaasMark())) {
                throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, MessageConstant.NOT_ALLOW_COPY, paasMenuEntity.getName());
            }
            // 校验应用中表单和流程表单启用的数量
            Integer count = validateFormMenuLengthInApp(corpid, menuCopyDTO.getTargetAppId());
            PaasMenuEntity menuEntity = new PaasMenuEntity();
            BeanUtil.copyProperties(paasMenuEntity, menuEntity);
            menuEntity.setAppId(menuCopyDTO.getTargetAppId());
            String name = paasMenuEntity.getName() + "_" + I18nMessageUtil.getMessage(I18nStringConstant.COPY_SUFFIX);
            if (name.length() > FORM_NAME_LENGTH) {
                throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, MessageConstant.FORM_NAME_LENGTH_TOO_LONG);
            }
            menuEntity.setName(name);
            menuEntity.setParentId(0L);
            menuEntity.setSort(count + 1);
            paasMenuModel.insert(menuEntity);
            // 记录日志
            String userName = menuCopyDTO.getLoginUserName();
            String memo = String.format(I18nMessageUtil.getMessage(LogMemoConstant.LOG_MEMO_USER_ADD_MENU), userName, paasMenuEntity.getName());
            mongoLogHelp.buildLog(corpid, menuCopyDTO.getUserId(), userName, OperateModuleTypeEnum.PAAS_MENU, OperateTypeEnum.NEW, menuEntity.getId().toString(), menuEntity.getName(), memo, menuCopyDTO.getHttpHeader());

            ApplicationCopyDTO applicationCopyDTO = new ApplicationCopyDTO();
            BeanUtil.copyProperties(menuCopyDTO, applicationCopyDTO);
            paasAppService.copyMenu(applicationCopyDTO, menuCopyDTO.getType(), menuEntity.getId(), menuCopyDTO.getTargetAppId(), menuEntity.getName());

            menuCopyVO.setMenuId(menuEntity.getId());
        } catch (XbbException e) {
            throw e;
        } catch (Exception e) {
            LOG.error("paasMenu数据库复制菜单出错", e);
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, SystemErrorCodeEnum.API_ERROR_100001.getMsg());
        }
        return menuCopyVO;
    }

    @Override
    public FormListInProcessVO formListInProcess(FormListInProcessDTO formListInProcessDTO) throws XbbException {
        FormListInProcessVO formListInProcessVO = new FormListInProcessVO();
        try {
            Map<String, Object> params = BeanUtil.convertBean2Map(formListInProcessDTO, true);
            List<PaasMenuEntity> menuList = paasMenuModel.list(params);
            if (menuList == null) {
                throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, MessageConstant.MENU_NOT_EXIST);
            }
            formListInProcessVO.setMenuList(menuList);
        } catch (XbbException e) {
            throw e;
        } catch (Exception e) {
            LOG.error("paasMenu数据库复制菜单出错", e);
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, SystemErrorCodeEnum.API_ERROR_100001.getMsg());
        }
        return formListInProcessVO;
    }

    @Override
    public MenuChangeStateVO changeState(MenuChangeStateDTO menuChangeStateDTO) throws XbbException {
        MenuChangeStateVO changeStateVO = new MenuChangeStateVO();
        Integer target = menuChangeStateDTO.getTarget();
        String alias = menuChangeStateDTO.getAlias();
        if (Objects.equals(alias, CompanyConfigEnum.TPLUS.getAlias())) {
            changeCompanyConfigState(menuChangeStateDTO);
        } else if (target.equals(MenuChangeStateDTO.TargetEnum.APP.getCode())) {
            changeAppState(menuChangeStateDTO);
        } else if (target.equals(MenuChangeStateDTO.TargetEnum.MENU.getCode())) {
            if (menuChangeStateDTO.getMenuId() == null) {
                throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, MessageConstant.CAN_NOT_BE_EMPTY, "menuId");
            }
            changeMenuState(menuChangeStateDTO);
            changeStateVO.setMenuId(menuChangeStateDTO.getMenuId());
        }
        // 清除当前登录人权限缓存
        String userKey = menuChangeStateDTO.getCorpid() + "____" + menuChangeStateDTO.getUserId();
        paasRedisHelper.removeValue(RedisPrefixConstant.PAAS_LOGIN_USER_INFO, userKey);
        // DTO中已经做了参数判断，不会执行到else逻辑
        changeStateVO.setAppId(menuChangeStateDTO.getAppId());
        changeStateVO.setEnable(menuChangeStateDTO.getEnable());

        return changeStateVO;
    }

    private void changeCompanyConfigState(MenuChangeStateDTO menuChangeStateDTO) throws XbbException {
        String alias = menuChangeStateDTO.getAlias();
        boolean enable = menuChangeStateDTO.getEnable();
        String corpid = menuChangeStateDTO.getCorpid();
        Integer enableInt = enable ? 1 : 0;
        CompanyConfigEnableDTO companyConfigEnableDTO = new CompanyConfigEnableDTO();
        companyConfigEnableDTO.setCorpid(corpid);
        companyConfigEnableDTO.setUserId(menuChangeStateDTO.getUserId());
        companyConfigEnableDTO.setLoginUserName(menuChangeStateDTO.getLoginUserName());
        companyConfigEnableDTO.setAlias(alias);
        companyConfigEnableDTO.setValue(enableInt.toString());
        companyConfigService.enable(companyConfigEnableDTO);

        apiCallBackService.tplusApiCallbackSet(corpid, enableInt);
    }

    @Override
    public MenuNewListVO list(MenuNewListDTO menuNewListDTO) throws XbbException {
        MenuNewListVO menuNewListVO = new MenuNewListVO();
        String corpid = menuNewListDTO.getCorpid();
        String userId = menuNewListDTO.getUserId();
        try {
            Map<String, Object> param = BeanUtil.convertBean2Map(menuNewListDTO);
            param.put("orderByStr", "sort");
            List<PaasAppEntity> appList = paasAppModel.list(param);
            if (Objects.isNull(appList)) {
                appList = new ArrayList<>();
            }
            Integer num = updatePackageRedisService.getUnusedNumPackageLimit(menuNewListDTO.getCorpid(), ValueAddedTypeEnum.CUSTOM_FORM_NUM);
            List<String> featureList = packageHelp.getFeatureList(menuNewListDTO.getCorpid());
            List<AppMenuListVO> commonFormList = new ArrayList<>();
            List<AppMenuListVO> productMenuList = new ArrayList<>();
            MenuConfigPojo menuConfigPojo = new MenuConfigPojo();
            menuConfigPojo.setPermissionFlag(true);
            menuConfigPojo.setSearchSelfConfig(true);
            menuConfigPojo.setSearchCompanyConfig(true);
            menuConfigPojo.setIsHomeList(1);
            Map<Long, List<AppMenuListVO>> menuListMap = proMenuHelp.getMenuList(menuNewListDTO, menuNewListVO, commonFormList,
                    productMenuList, menuConfigPojo, featureList, num);
            List<PaasAppMenuVO> appVOList = new ArrayList<>();
            for (HomeMenuEnum homeMenuEnum : HomeMenuEnum.values()) {
                if (PaasConstant.LEFT_POSITION.equals(homeMenuEnum.getPosition())) {
                    PaasAppMenuVO paasAppMenuVO = new PaasAppMenuVO();
                    paasAppMenuVO.setName(homeMenuEnum.getName());
                    paasAppMenuVO.setIcon(homeMenuEnum.getAccessLinkEnum().getIcon());
                    paasAppMenuVO.setAlias(homeMenuEnum.getAlias());
                    paasAppMenuVO.setUrl(homeMenuEnum.getAccessLinkEnum().getUrl());
                    if (HomeMenuEnum.LEFT_HOME.getAlias().equals(homeMenuEnum.getAlias()) && PlatFormEnum.DINGTALK.getValue().equals(menuNewListDTO.getPlatform())) {
                        continue;
                    }
                    if (HomeMenuEnum.COMMON_FORM.getAlias().equals(homeMenuEnum.getAlias()) && commonFormList.isEmpty()) {
                        continue;
                    }
                    if (HomeMenuEnum.LEFT_HOME.getAlias().equals(homeMenuEnum.getAlias())) {
                        continue;
                    }
                    if (HomeMenuEnum.COMMON_FORM.getAlias().equals(homeMenuEnum.getAlias())) {
                        paasAppMenuVO.setSubMenuList(proMenuHelp.sort(commonFormList));
                        appVOList.add(paasAppMenuVO);
                    } else {
                        appVOList.add(paasAppMenuVO);
                    }
                }
            }
            // 获取通话记录的权限
            Boolean hasCallCenterPermission = false;
            if (Objects.equals(PlatFormEnum.WEB.getValue(), menuNewListDTO.getPlatform())) {
                // 呼叫中心
                CallCenterModuleDTO callCenterModuleDTO = new CallCenterModuleDTO();
                BeanUtil.copyProperties(menuNewListDTO, callCenterModuleDTO);
                CallCenterModuleVO callCenterModuleVO = callCenterCommonService.module(callCenterModuleDTO);
                Integer moduleType = callCenterModuleVO.getModuleType();
                if (Objects.nonNull(moduleType)) {
                    CallCenterAccountUserInfoDTO callCenterAccountUserInfoDTO = new CallCenterAccountUserInfoDTO();
                    BeanUtil.copyProperties(menuNewListDTO, callCenterAccountUserInfoDTO);
                    callCenterAccountUserInfoDTO.setModuleType(moduleType);
                    CallCenterAccountUserInfoVO callCenterAccountUserInfoVO = callCenterAccountService.getByXbbUserInfo(callCenterAccountUserInfoDTO);
                    if (Objects.nonNull(callCenterAccountUserInfoVO)) {
                        hasCallCenterPermission = callCenterAccountUserInfoVO.getIsAdmin() == 1;
                    }
                }
            }
            menuNewListVO.setMenuList(appVOList);
            UserVO loginUser = menuNewListDTO.getLoginUser();
            Boolean isAdminOrBoss = loginUser.isAdminOrBoss();
            Set<String> permissionAlias = loginUser.getPermSet();
            if (permissionAlias == null) {
                permissionAlias = new HashSet<>();
            }
            Set<Long> paasAppIdSet = ProPermissionHelp.getPaasViewAppIdSet(loginUser.getPaasPermissions());
            // 判断员工是否能使用搜客
            SearchCustomerUserEntity searchCustomerUserEntity = searchCustomerUserModel.getByKey(loginUser.getUserId(), loginUser.getCorpid());
            // 判断搜客是否过期
            SearchCustomerCompanyEntity soukeEntity = searchCustomerCompanyModel.getByCorpid(loginUser.getCorpid(), SoukeMealEnum.SOUKE.getType());
            // 判断工单应用是否启用
            Boolean isWorkOrderUse = paasAppService.validateAppEnable(null, XbbRefTypeEnum.WORK_ORDER.getAlias(), SaasMarkEnum.SAAS.getCode(), menuNewListDTO.getCorpid());
            if (soukeEntity == null || soukeEntity.getExtraExpiry() <= DateUtil.getInt()) {
                searchCustomerUserEntity = null;
            }
            Boolean pastDue = feeLogService.workOrderV2PastDue(corpid);
            //判断套餐是否是标准版
            Boolean feeTypeIsStandardOrAppIsClosed = feeTypeIsStandardOrAppIsClosed(menuNewListDTO.getCorpid());
            // 移动端不展示合同比对
            if (Objects.equals(menuNewListDTO.getPlatform(), PlatFormEnum.DINGTALK.getValue())) {
                appList.removeIf(item -> Objects.equals(item.getAlias(), XbbRefTypeEnum.CONTRACT_COMPARE.getAlias()));
                appList.removeIf(item -> Objects.equals(item.getAlias(), XbbRefTypeEnum.CONTRACT_TEMPLATE_BASE.getAlias()));
            }
            for (PaasAppEntity item : appList) {
                String alias = item.getAlias();
                if (SaasMarkEnum.SAAS.getCode().equals(item.getSaasMark()) && !Objects.equals(item.getAlias(), SystemAppMenuEnum.SEARCH_CUSTOMER.getAlias())) {
                    if (StringUtil.isEmpty(alias)) {
                        continue;
                    }
                    if (Objects.equals(item.getAlias(), SystemAppMenuEnum.BUNDLE.getAlias())) {
                        alias = ProPermissionAliasEnum.SALE_BUNDLE.getAlias();
                    }
                    if (Objects.equals(item.getAlias(), SystemAppMenuEnum.GROUP_MESSAGE.getAlias())) {
                        alias = ProPermissionAliasEnum.SMS_APP.getAlias();
                    }
                    if (Objects.equals(item.getAlias(), SystemAppMenuEnum.PRODUCT.getAlias())) {
                        alias = ProPermissionAliasEnum.PRODUCT_MANAGEMENT.getAlias();
                    }
                    if (Objects.equals(item.getAlias(), SystemAppMenuEnum.CONTRACT_TEMPLATE_BASE.getAlias())) {
                        alias = ProPermissionAliasEnum.CONTRACT_BASE_VIEW.getAlias();
                    }
                    Boolean hasCall = SystemAppMenuEnum.CALL_CENTER.getAlias().equals(alias)
                            || SystemAppMenuEnum.CALL_CENTER_DU_YAN.getAlias().equals(alias);
                    // 酷应用菜单所有人可见
                    if (!isAdminOrBoss && !permissionAlias.contains(alias) && !hasCall && !Objects.equals(alias, XbbRefTypeEnum.COOL_APP.getAlias())) {
                        continue;
                    }
                    if (Objects.equals(SystemAppMenuEnum.PRODUCT.getAlias(), alias)) {
                        if (!isAdminOrBoss && !permissionAlias.contains(ProPermissionAliasEnum.PRODUCT_MANAGEMENT.getAlias())) {
                            continue;
                        }
                    }
                    //"市场管理"模块，标准版是不能没有的
                    if (Objects.equals(SystemAppMenuEnum.MARKET_MANAGEMENT.getAlias(), alias) && feeTypeIsStandardOrAppIsClosed) {
                        continue;
                    }
                    // saas 应用
                } else if (SaasMarkEnum.PAAS.getCode().equals(item.getSaasMark())) {
                    if (!isAdminOrBoss && !paasAppIdSet.contains(item.getId())) {
                        continue;
                    }
                }
                if (Objects.equals(XbbRefTypeEnum.WORK_ORDER_V2_CENTER.getAlias(), alias) && pastDue) {
                    commonFormList.removeIf(common -> Objects.equals(item.getId(), common.getAppId()));
                    continue;
                }
                PaasAppMenuVO paasAppMenuVO = new PaasAppMenuVO();
                BeanUtil.copyProperties(item, paasAppMenuVO);
                List<AppMenuListVO> appMenuList = menuListMap.get(item.getId());
                if (Objects.isNull(appMenuList) || appMenuList.isEmpty()) {
                    paasAppMenuVO.setUrl(AccessLinkEnum.NO_FORM.getUrl());
                    appMenuList = new ArrayList<>();
                }
                if (!featureList.contains(FeaturesEnum.APPLICATION.getAlias()) && Objects.equals(SaasMarkEnum.PAAS.getCode(), item.getSaasMark())) {
                    paasAppMenuVO.setPackageLimit(1);
                    paasAppMenuVO.setMessage(String.format(I18nMessageUtil.getMessage(PackageConstant.APPLICATION_PACKAGE_LIMIT_MESSAGE), num));
                }
                paasAppMenuVO.setSubMenuList(appMenuList);
                // 特殊逻辑，工单的菜单不启用，在应用级菜单拼接url
                if (WorkOrderMenuEnum.WORK_ORDER.getAlias().equals(paasAppMenuVO.getAlias())) {
                    if (PlatFormEnum.WEB.getValue().equals(menuNewListDTO.getPlatform())) {
                        if (CollectionsUtil.isEmpty(menuListMap.get(item.getId()))) {
                            continue;
                        }
                        List<AppMenuListVO> menuList = menuListMap.get(item.getId());
                        String workOrderUrl = AccessLinkEnum.WORK_ORDER.getUrl();
                        StringBuilder url = new StringBuilder(workOrderUrl)
                                .append("?subBusinessType=").append(WorkOrderMenuEnum.WORK_ORDER.getCode())
                                .append("&appId=").append(paasAppMenuVO.getId())
                                .append("&saasMark=").append(paasAppMenuVO.getSaasMark());
                        if (Objects.nonNull(menuList) && !menuList.isEmpty()) {
                            Long menuId = null;
                            for (AppMenuListVO appMenuListVO : menuList) {
                                if (Objects.equals(appMenuListVO.getAlias(), XbbRefTypeEnum.WORK_ORDER.getAlias())) {
                                    menuId = appMenuListVO.getId();
                                    // 30705 Web更改工单菜单名称后，左侧导航菜单的文案展示错误。
                                    // paasAppMenuVO.setName(appMenuListVO.getName());
                                    paasAppMenuVO.setColor(appMenuListVO.getColor());
                                    paasAppMenuVO.setIcon(appMenuListVO.getIcon());
                                }
                            }
                            if (Objects.nonNull(menuId)) {
                                url = url.append("&menuId=").append(menuId);
                            }
                        }
                        paasAppMenuVO.setSubMenuList(new ArrayList<>());
                        paasAppMenuVO.setUrl(url.toString());
                    }

                } else if (SystemAppMenuEnum.CALL_CENTER.getAlias().equals(paasAppMenuVO.getAlias())
                        || SystemAppMenuEnum.CALL_CENTER_DU_YAN.getAlias().equals(paasAppMenuVO.getAlias())) {
                    // 没有通话记录的权限或者是dingtalk
                    if (!hasCallCenterPermission || PlatFormEnum.DINGTALK.getValue().equals(menuNewListDTO.getPlatform())) {
                        continue;
                    } else {
                        List<AppMenuListVO> subMenuList = new ArrayList<>();
                        AppMenuListVO appMenuListVO = new AppMenuListVO();
                        appMenuListVO.setSort(0);
                        appMenuListVO.setAppId(item.getId());
                        appMenuListVO.setName(CallCenterMenuEnum.CALL_CENTER_CALL_LOG.getName());
                        appMenuListVO.setIcon(AccessLinkEnum.CALL_CENTER_CALL_LOG.getIcon());
                        appMenuListVO.setColor(AccessLinkEnum.CALL_CENTER_CALL_LOG.getColor());
                        appMenuListVO.setUrl(AccessLinkEnum.CALL_CENTER_CALL_LOG.getUrl());
                        subMenuList.add(appMenuListVO);
                        paasAppMenuVO.setSubMenuList(subMenuList);
                    }
                } else if (SystemAppMenuEnum.GROUP_MESSAGE.getAlias().equals(paasAppMenuVO.getAlias())) {
                    if (PlatFormEnum.DINGTALK.getValue().equals(menuNewListDTO.getPlatform())) {
                        continue;
                    }
                } else if (SystemAppMenuEnum.ESIGN.getAlias().equals(paasAppMenuVO.getAlias())) {
                    continue;
                } else if (SystemAppMenuEnum.SEARCH_CUSTOMER.getAlias().equals(alias)) {
                    //判断精线索是否可用
                    FineClueUserEntity fineClueUserEntity = fineClueUserModel.getUserByStaff(loginUser.getCorpid(), loginUser.getUserId(), 1);
                    FineClueCompanyEntity fineClueCompanyEntity = fineClueCompanyModel.getByCorpid(loginUser.getCorpid(), FineClueEnum.FINE_CLUE.getType());
                    if (fineClueUserEntity != null && fineClueCompanyEntity != null && fineClueCompanyEntity.getExtraExpiry() > DateUtil.getInt()) {
//                        if (!PlatFormEnum.DINGTALK.getValue().equals(menuNewListDTO.getPlatform())){
                        appVOList.add(paasAppMenuVO);
//                        }
                        continue;
                    }
                    // 增加搜客试用套餐
                    if (soukeEntity != null && soukeEntity.getExtraExpiry() - soukeEntity.getAddTime() < 4 * RedisConstant.LONG_DURATION
                            && soukeEntity.getExtraExpiry() > DateUtil.getInt()) {
                        if (searchCustomerUserEntity == null) {
                            searchCustomerUserEntity = new SearchCustomerUserEntity();
                        }
                        searchCustomerUserEntity.setStaff(1);
                    }
                    if (searchCustomerUserEntity == null || searchCustomerUserEntity.getStaff() == 0) {
                        continue;
                    }
                    List<AppMenuListVO> subMenuList = paasAppMenuVO.getSubMenuList();
                    if (CollectionUtils.isEmpty(subMenuList)) {
                        continue;
                    }
                    if (PlatFormEnum.DINGTALK.getValue().equals(menuNewListDTO.getPlatform())) {
                        subMenuList.removeIf(appMenuListVO -> XbbRefTypeEnum.RECYCLE_BIN.getAlias().equals(appMenuListVO.getAlias()));
                    }

                } else if (SystemAppMenuEnum.JXC.getAlias().equals(paasAppMenuVO.getAlias())) {
                    if (!isWorkOrderUse) {
                        List<AppMenuListVO> subMenuList = paasAppMenuVO.getSubMenuList();
                        subMenuList.forEach(subMenuItem -> {
                            if (Objects.equals(XbbRefTypeEnum.OUTSTOCK.getAlias(), subMenuItem.getAlias())) {
                                subMenuItem.getSubMenuList().removeIf(appMenuListVO -> XbbRefTypeEnum.WORK_ORDER_OUTSTOCK.getAlias().equals(appMenuListVO.getAlias()));
                            }
                        });

                    }
                } else if (SystemAppMenuEnum.BUNDLE.getAlias().equals(paasAppMenuVO.getAlias())) {
                    if (PlatFormEnum.DINGTALK.getValue().equals(menuNewListDTO.getPlatform())) {
                        continue;
                    }
                } else if (SystemAppMenuEnum.FINE_CLUE.getAlias().equals(paasAppMenuVO.getAlias())) {
                    //判断精线索是否可用
                    FineClueUserEntity fineClueUserEntity = fineClueUserModel.getUserByStaff(loginUser.getCorpid(), loginUser.getUserId(), 1);
                    FineClueCompanyEntity fineClueCompanyEntity = fineClueCompanyModel.getByCorpid(loginUser.getCorpid(), FineClueEnum.FINE_CLUE.getType());
                    if (fineClueUserEntity == null || fineClueCompanyEntity == null || fineClueCompanyEntity.getExtraExpiry() <= DateUtil.getInt()) {
                        continue;
                    }
                } else if (SystemAppMenuEnum.DISTRIBUTOR.getAlias().equals(paasAppMenuVO.getAlias())) {
                    List<AppMenuListVO> subMenuList = paasAppMenuVO.getSubMenuList();
                    subMenuList.forEach(subMenuItem -> {
                        subMenuItem.setDistributorMark(DistributorMarkEnum.DISTRIBUTOR.getCode());
                    });
                } else if (SystemAppMenuEnum.ORDER_CENTER.getAlias().equals(paasAppMenuVO.getAlias())) {
                    List<AppMenuListVO> subMenuList = paasAppMenuVO.getSubMenuList();
                    subMenuList.forEach(subMenuItem -> {
                        subMenuItem.setDistributorMark(DistributorMarkEnum.DISTRIBUTOR.getCode());
                    });
                } else if (SystemAppMenuEnum.CONTRACT_COMPARE.getAlias().equals(paasAppMenuVO.getAlias())) {
                    Integer status = contractCompareUtil.getContractCompareStatus(corpid);
                    // 非试用版
                    if (!Objects.equals(status, ContractCompareFeeStatusEnum.TRIAL.getType())) {
                        Integer compareStaff = contractCompareUtil.getContractCompareStaff(corpid, userId);
                        // 坐席未开启，不展示合同比对菜单
                        if (Objects.equals(compareStaff, BasicConstant.ZERO)) {
                            continue;
                        }
                    }
                }else if (SystemAppMenuEnum.CONTRACT_TEMPLATE_BASE.getAlias().equals(paasAppMenuVO.getAlias())
                        &&PlatFormEnum.WEB.getValue().equals(menuNewListDTO.getPlatform())) {
                    String contractTemplateBase = AccessLinkEnum.CONTRACT_TEMPLATE_BASE.getUrl();
                    StringBuilder url = new StringBuilder(contractTemplateBase)
                            .append("?subBusinessType=").append(XbbRefTypeEnum.CONTRACT_TEMPLATE_BASE.getCode())
                            .append("&appId=").append(paasAppMenuVO.getId())
                            .append("&saasMark=").append(paasAppMenuVO.getSaasMark());
                    paasAppMenuVO.setSubMenuList(new ArrayList<>());
                    paasAppMenuVO.setUrl(url.toString());
                }
                appVOList.add(paasAppMenuVO);
            }
            // 增加阿里云呼叫中心菜单
            // 判断是否有阿里云呼叫中心权限
            IsActiveAliyunCallVO activeAliyunCall1 = callCenterCommonService.isActiveAliyunCall(corpid, userId);
            if (Objects.nonNull(activeAliyunCall1) && activeAliyunCall1.IsActiveAliyunAndHasRole()) {
                PaasAppMenuVO menuList = callCenterCommonService.getMenuList(menuNewListDTO.getPlatform(), activeAliyunCall1.getRole(), activeAliyunCall1.getFacilitators());
                if (Objects.nonNull(menuList)) {
                    appVOList.add(menuList);
                }
            }
            //搜客过期 || 搜客应用关闭||无搜客坐席，去除常用表单中搜客子菜单
            PaasAppEntity appEntity = paasAppModel.getByAlias(ProPermissionAliasEnum.SOUKE.getAlias(), corpid);
            FineClueCompanyEntity companyEntity = fineClueCompanyModel.getByCorpid(corpid, FineClueEnum.FINE_CLUE.getType());
            FineClueUserEntity clueUserEntity = fineClueUserModel.getByKey(corpid, userId);
            if ((!fineClueHelp.fineClueUsable(corpid, FineClueEnum.FINE_CLUE)) || ((Objects.nonNull(appEntity) && (Objects.equals(appEntity.getEnable(), BasicConstant.ZERO)))) || ((Objects.nonNull(companyEntity)) && Objects.isNull(clueUserEntity))) {
                List<String> souKeAlias = Arrays.asList(XbbRefTypeEnum.FINE_CLUE_QUERY_COMPANY.getAlias(),
                        XbbRefTypeEnum.FINE_CLUE_QUERY_CLUE.getAlias(), XbbRefTypeEnum.FINE_CLUE_MAP_QUERY.getAlias(), XbbRefTypeEnum.FINE_CLUE_BATCH_QUERY.getAlias());
                Iterator<PaasAppMenuVO> it = appVOList.iterator();
                while (it.hasNext()) {
                    PaasAppMenuVO appMenuVO = it.next();
                    if (Objects.equals(appMenuVO.getAlias(), "commonForm")) {
                        List<AppMenuListVO> subMenuList = appMenuVO.getSubMenuList();
                        Iterator<AppMenuListVO> iterator = subMenuList.iterator();
                        while (iterator.hasNext()) {
                            AppMenuListVO menuListVO = iterator.next();
                            if (souKeAlias.contains(menuListVO.getAlias())) {
                                iterator.remove();
                                break;
                            }
                        }
                    }
                }
            }
            //渲染跨应用移动菜单的处理
            if (commonHelp.isOpenMenuWhite(corpid)) {
                proMenuHelp.formatAppMenuVoList(appVOList, corpid);
            }
            menuNewListVO.setMenuList(appVOList);
        } catch (XbbException e) {
            throw e;
        } catch (Exception e) {
            LOG.error("menuService.list获取菜单列表：", e);
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, SystemErrorCodeEnum.API_ERROR_100001.getMsg());
        }
        //移动端搜客只有3个从菜单,去除批量查企业
        if (Objects.equals(menuNewListDTO.getPlatform(), PlatFormEnum.DINGTALK.getValue())) {
            List<PaasAppMenuVO> menuList = menuNewListVO.getMenuList();
            for (PaasAppMenuVO paasAppMenuVO : menuList) {
                if (Objects.equals(paasAppMenuVO.getAlias(), ControlCenterMenuEnum.SEARCH_CUSTOMER.getAlias())) {
                    List<AppMenuListVO> subMenuList = paasAppMenuVO.getSubMenuList();
                    subMenuList.removeIf(s -> Objects.equals(s.getAlias(), FineClueMenuEnum.FINE_CLUE_BATCH_QUERY.getAlias()));
                }
            }
        }


        return menuNewListVO;
    }

    @Override
    public AppMenuFormIdVO getAppFormMenuId(AppMenuFormIdDTO appMenuFormIdDTO) throws XbbException {
        AppMenuFormIdVO appMenuFormIdVO = new AppMenuFormIdVO();
        try {
            Map<String, Object> param = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
            param.put("enable", BasicConstant.ONE);
            param.put(StringConstant.CORPID, appMenuFormIdDTO.getCorpid());
            param.put("del", DelEnum.NORMAL.getDel());
            List<PaasMenuEntity> menuList = paasMenuModel.list(param);
            if (menuList == null) {
                throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, MessageConstant.MENU_NOT_EXIST);
            }
            List<Long> menuIds = new ArrayList<>();
            menuList.forEach(item -> {
                menuIds.add(item.getId());
            });
            param.clear();
            param.put(StringConstant.CORPID, appMenuFormIdDTO.getCorpid());
            param.put("enable", BasicConstant.ONE);
            param.put(StringConstant.DEL, DelEnum.NORMAL.getDel());
            param.put("saasMark", BasicConstant.ONE);
            param.put("businessType", appMenuFormIdDTO.getBusinessType());
            param.put("menuIdIn", menuIds);
            List<PaasFormEntityExt> formEntities = paasFormModel.list(param);
            if (Objects.isNull(formEntities)) {
                LOG.error("menuService.getAppFormMenuId获取AppMenuFoemId：formEntities为null");
                return appMenuFormIdVO;
            }
            // 如果是查看签到，则过滤掉权限校验
            if ((!Objects.equals(appMenuFormIdDTO.getSubBusinessType(), XbbRefTypeEnum.SIGNIN.getCode()))) {
                paasFormService.removeByPermission(formEntities, appMenuFormIdDTO.getLoginUser());
                if (CollectionUtils.isEmpty(formEntities)) {
                    LOG.error("menuService.getAppFormMenuId获取AppMenuFoemId：formEntities为空,");
                    return appMenuFormIdVO;
                }
            }
            List<AppMenuFormIdPojo> appMenuFormIdPojos = new ArrayList<>();
            formEntities.forEach(formEntitie -> {
                AppMenuFormIdPojo appMenuFormIdPojo = new AppMenuFormIdPojo();
                BeanUtil.copyProperties(formEntitie, appMenuFormIdPojo);
                appMenuFormIdPojo.setFormId(formEntitie.getId());
                appMenuFormIdPojos.add(appMenuFormIdPojo);
            });
            appMenuFormIdVO.setAppMenuFornIdList(appMenuFormIdPojos);

            List<ListTopButtonEnum> topButtonEnumList = ListTopButtonEnum.getByBusinessType(appMenuFormIdDTO.getSubBusinessType());
            List<ButtonPojo> topButtonList = new ArrayList<>();
            for (ListTopButtonEnum topButtonEnum : topButtonEnumList) {
                ButtonPojo buttonPojo = new ButtonPojo();
                BeanUtil.copyProperties(topButtonEnum.getAnEnum(), buttonPojo);
                topButtonList.add(buttonPojo);
            }
            if (Objects.nonNull(topButtonList) && !topButtonList.isEmpty()) {
                for (ButtonPojo buttonPojo : topButtonList) {
                    if (Objects.nonNull(buttonPojo) && Objects.equals(buttonPojo.getAttr(), SaasButtonEnum.ADD.getAttr())) {
                        appMenuFormIdVO.setAddPermission(true);
                    }
                }
            }
        } catch (Exception e) {
            LOG.error("menuService.getAppFormMenuId获取AppMenuFoemId：", e);
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, SystemErrorCodeEnum.API_ERROR_100001.getMsg());
        }

        return appMenuFormIdVO;
    }


    @Override
    public MenuTopVO topMenuList(MenuTopDTO menuTopDTO) throws XbbException {
        MenuTopVO menuTopVO = new MenuTopVO();
        try {
            Integer unRead = null;
            MessageCountDTO messageCountDTO = new MessageCountDTO(1, 100, menuTopDTO.getCorpid(), menuTopDTO.getUserId());
            MessageCountVO messageCountVO = pushLinkService.countUnread(messageCountDTO);
            if (Objects.nonNull(messageCountVO)) {
                unRead = messageCountVO.getCount();
            }
            Boolean hasProcessPermission = menuTopDTO.getLoginUser().getPermSet().contains(ProPermissionAliasEnum.PROCESS.getAlias());
            Integer processUnDeal = null;
            boolean openWorkflow = commonHelp.isOpenWorkFlow(menuTopDTO.getCorpid());
            if (hasProcessPermission) {
                if (openWorkflow) {
                    // 新工作流
                    WorkflowNodeTaskCountDTO workflowNodeTaskCountDTO = new WorkflowNodeTaskCountDTO();
                    workflowNodeTaskCountDTO.setCorpid(menuTopDTO.getCorpid());
                    workflowNodeTaskCountDTO.setUserId(menuTopDTO.getUserId());
                    WorkflowNodeTaskCountVO workflowNodeTaskCountVO = workflowApproveListPageOperationService.count(workflowNodeTaskCountDTO);
                    if (Objects.nonNull(workflowNodeTaskCountVO)) {
                        processUnDeal = workflowNodeTaskCountVO.getCc() + workflowNodeTaskCountVO.getCreate() + workflowNodeTaskCountVO.getTodo();
                    }
                } else {
                    // 老审批
                    ProcessNodeTaskCountDTO processNodeTaskCountDTO = new ProcessNodeTaskCountDTO();
                    BeanUtil.copyProperties(menuTopDTO, processNodeTaskCountDTO);
                    ProcessNodeTaskCountVO processNodeTaskCountVO = paasProcessNodeTaskService.count(processNodeTaskCountDTO);
                    if (Objects.nonNull(processNodeTaskCountVO)) {
                        processUnDeal = processNodeTaskCountVO.getCc() + processNodeTaskCountVO.getCreate() + processNodeTaskCountVO.getTodo();
                    }
                }
            }
            UserVO userVO = menuTopDTO.getLoginUser();
            List<HomeMenuTopVO> topCenterList = new ArrayList<>();
            List<HomeMenuTopVO> topRightList = new ArrayList<>();
            for (HomeMenuEnum homeMenuEnum : HomeMenuEnum.values()) {
                String permissionAlias = homeMenuEnum.getPermissionAlias();
                if (!userVO.isAdminOrBoss() && StringUtil.isNotEmpty(permissionAlias)
                        && !ProPermissionHelp.hasThisPermission(userVO, permissionAlias)) {
                    continue;
                }
                HomeMenuTopVO homeMenuTopVO = new HomeMenuTopVO();
                if (Objects.equals(homeMenuEnum, HomeMenuEnum.WORKFLOW)) {
                    if (openWorkflow) {
                        homeMenuTopVO.setUrl(AccessLinkEnum.NEW_WORKFLOW.getUrl());
                    } else {
                        homeMenuTopVO.setUrl(homeMenuEnum.getAccessLinkEnum().getUrl());
                    }
                } else {
                    homeMenuTopVO.setUrl(homeMenuEnum.getAccessLinkEnum().getUrl());
                }
                homeMenuTopVO.setIcon(homeMenuEnum.getAccessLinkEnum().getIcon());
                if (PaasConstant.TOP_CENTER_POSITION.equals(homeMenuEnum.getPosition())) {
                    homeMenuTopVO.setName(homeMenuEnum.getName());
                    homeMenuTopVO.setAlias(homeMenuEnum.getAlias());
                    topCenterList.add(homeMenuTopVO);
                } else if (PaasConstant.TOP_RIGHT_POSITION.equals(homeMenuEnum.getPosition())) {
                    if (Objects.equals(homeMenuEnum.getAlias(), HomeMenuEnum.MESSAGE.getAlias()) && Objects.nonNull(unRead) && !Objects.equals(unRead, 0)) {
                        if (unRead <= 99) {
                            homeMenuTopVO.setCount(String.valueOf(unRead));
                        } else {
                            homeMenuTopVO.setCount("99+");
                        }
                    } else if (Objects.equals(homeMenuEnum.getAlias(), HomeMenuEnum.WORKFLOW.getAlias()) && hasProcessPermission
                            && Objects.nonNull(processUnDeal) && !Objects.equals(processUnDeal, 0)) {
                        // 流程权限存在，才能有此记录
                        if (processUnDeal <= 99) {
                            homeMenuTopVO.setCount(String.valueOf(processUnDeal));
                        } else {
                            homeMenuTopVO.setCount("99+");
                        }
                    }
                    homeMenuTopVO.setName(homeMenuEnum.getName());
                    homeMenuTopVO.setAlias(homeMenuEnum.getAlias());
                    topRightList.add(homeMenuTopVO);
                }
            }
            menuTopVO.setTopCenterList(topCenterList);
            menuTopVO.setTopRightList(topRightList);
        } catch (Exception e) {
            LOG.error("menuService.topMenuList获取顶部信息列表出错：", e);
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, SystemErrorCodeEnum.API_ERROR_100001.getMsg());
        }
        return menuTopVO;
    }

    @Override
    public MenuSetVO set(MenuSetDTO menuSetDTO) throws XbbException {
        MenuSetVO menuSetVO = new MenuSetVO();
        try {
            List<UserConfigAddDTO> userConfigAddDTOList = new ArrayList<>();
            List<Long> menuIdIn = new ArrayList<>();
            List<Long> commonFormList = menuSetDTO.getCommonFormList();
            if (Objects.nonNull(commonFormList)) {
                menuIdIn.addAll(commonFormList);
            }
            List<Long> quickNewList = menuSetDTO.getQuickNewFormList();
            if (Objects.nonNull(quickNewList)) {
                menuIdIn.addAll(menuSetDTO.getQuickNewFormList());
            }
            List<PaasMenuEntity> menuList = new ArrayList<>();
            if (!menuIdIn.isEmpty()) {
                Map<String, Object> param = new HashMap<>(menuIdIn.size());
                param.put("idIn", menuIdIn);
                param.put("corpid", menuSetDTO.getCorpid());
                param.put("del", DelEnum.NORMAL.getDel());
                menuList = paasMenuModel.findEntitys(param);
                if (Objects.isNull(menuList)) {
                    throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, SystemErrorCodeEnum.API_ERROR_100001.getMsg());
                }
                for (PaasMenuEntity paasMenuEntity : menuList) {
                    if (Objects.equals(XbbRefTypeEnum.CUSTOMER_RECYCLE.getAlias(), paasMenuEntity.getAlias()) || Objects.equals(XbbRefTypeEnum.CLUE_RECYCLE.getAlias(), paasMenuEntity.getAlias())) {
                        throw new XbbException(ProErrorCodeEnum.API_ERROR_260024);
                    }
                }
            }

            Map<Long, PaasMenuEntity> menuMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
            for (PaasMenuEntity item : menuList) {
                menuMap.put(item.getId(), item);
            }

            if (Objects.nonNull(commonFormList)) {
                UserConfigAddDTO commonForm = new UserConfigAddDTO();
                commonForm.setConfigAlias(UserConfigEnum.COMMON_FORM.getAlias());
                commonForm.setConfigName(UserConfigEnum.COMMON_FORM.getName());
                List<MenuReturnPojo> menuReturnList = new ArrayList<>();
                for (int i = 0; i < commonFormList.size(); i++) {
                    PaasMenuEntity paasMenuEntity = menuMap.get(commonFormList.get(i));
                    MenuReturnPojo menuReturnPojo = new MenuReturnPojo();
                    BeanUtil.copyProperties(paasMenuEntity, menuReturnPojo);
                    menuReturnPojo.setMenuId(paasMenuEntity.getId());
                    menuReturnPojo.setSort(i);
                    menuReturnList.add(menuReturnPojo);
                }
                commonForm.setConfigValue(JSON.toJSONString(menuReturnList));
                userConfigAddDTOList.add(commonForm);
            }

            if (Objects.nonNull(quickNewList)) {
                UserConfigAddDTO quickNewForm = new UserConfigAddDTO();
                quickNewForm.setConfigAlias(UserConfigEnum.QUICK_NEW_FORM.getAlias() + "_" + menuSetDTO.getPlatform());
                quickNewForm.setConfigName(UserConfigEnum.QUICK_NEW_FORM.getName());
                List<MenuReturnPojo> menuReturnList = new ArrayList<>();
                for (int i = 0; i < quickNewList.size(); i++) {
                    PaasMenuEntity paasMenuEntity = menuMap.get(quickNewList.get(i));
                    MenuReturnPojo menuReturnPojo = new MenuReturnPojo();
                    BeanUtil.copyProperties(paasMenuEntity, menuReturnPojo);
                    menuReturnPojo.setMenuId(paasMenuEntity.getId());
                    menuReturnPojo.setSort(i);
                    menuReturnList.add(menuReturnPojo);
                }
                quickNewForm.setConfigValue(JSON.toJSONString(menuReturnList));
                userConfigAddDTOList.add(quickNewForm);
            }
            if (!userConfigAddDTOList.isEmpty()) {
                UserConfigAddBatchDTO userConfigAddBatchDTO = new UserConfigAddBatchDTO();
                BeanUtil.copyProperties(menuSetDTO, userConfigAddBatchDTO);
                userConfigAddBatchDTO.setUserConfigList(userConfigAddDTOList);
                userConfigService.saveBatch(userConfigAddBatchDTO);
            }
        } catch (XbbException e) {
            throw e;
        } catch (Exception e) {
            LOG.error("menuService.set菜单设置出错：", e);
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, SystemErrorCodeEnum.API_ERROR_100001.getMsg());
        }
        return menuSetVO;
    }

    @Override
    public ControlMenuSetVO controlSet(ControlMenuSetDTO controlMenuSetDTO) throws XbbException {
        ControlMenuSetVO menuSetVO = new ControlMenuSetVO();
        try {
            List<CompanyConfigAddDTO> userConfigAddDTOList = getConfigList(controlMenuSetDTO.getCorpid(), controlMenuSetDTO.getCommonFormList(),
                    controlMenuSetDTO.getQuickNewFormList(), controlMenuSetDTO.getPlatform());
            if (!userConfigAddDTOList.isEmpty()) {
                CompanyConfigAddBatchDTO companyConfigAddBatchDTO = new CompanyConfigAddBatchDTO();
                BeanUtil.copyProperties(controlMenuSetDTO, companyConfigAddBatchDTO);
                companyConfigAddBatchDTO.setUserConfigList(userConfigAddDTOList);
                companyConfigService.saveBatch(companyConfigAddBatchDTO);
            }
        } catch (XbbException e) {
            throw e;
        } catch (Exception e) {
            LOG.error("menuService.set菜单设置出错：", e);
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, SystemErrorCodeEnum.API_ERROR_100001.getMsg());
        }
        return menuSetVO;
    }

    private List<CompanyConfigAddDTO> getConfigList(String corpid, List<Long> commonFormList, List<Long> quickNewList, String platForm) throws XbbException {
        List<Long> menuIdIn = new ArrayList<>();
        if (Objects.nonNull(commonFormList)) {
            menuIdIn.addAll(commonFormList);
        }
        if (Objects.nonNull(quickNewList)) {
            menuIdIn.addAll(quickNewList);
        }
        List<PaasMenuEntity> menuList = new ArrayList<>();
        if (!menuIdIn.isEmpty()) {
            Map<String, Object> param = new HashMap<>(menuIdIn.size());
            param.put("idIn", menuIdIn);
            param.put("del", DelEnum.NORMAL.getDel());
            param.put("corpid", corpid);

            menuList = paasMenuModel.findEntitys(param);
            if (Objects.isNull(menuList)) {
                throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, SystemErrorCodeEnum.API_ERROR_100001.getMsg());
            }
            for (PaasMenuEntity paasMenuEntity : menuList) {
                if (Objects.equals(XbbRefTypeEnum.CUSTOMER_RECYCLE.getAlias(), paasMenuEntity.getAlias()) || Objects.equals(XbbRefTypeEnum.CLUE_RECYCLE.getAlias(), paasMenuEntity.getAlias())) {
                    throw new XbbException(ProErrorCodeEnum.API_ERROR_260024);
                }
                if (Objects.equals(XbbRefTypeEnum.MARKETING_ACTIVITY.getAlias(), paasMenuEntity.getAlias()) || Objects.equals(XbbRefTypeEnum.MARKETING_ACTIVITY_MANAGEMENT.getAlias(), paasMenuEntity.getAlias())
                        || Objects.equals(XbbRefTypeEnum.PROMOTION_ACTIVITY.getAlias(), paasMenuEntity.getAlias()) || Objects.equals(XbbRefTypeEnum.PROMOTION_ACTIVITY_MANAGEMENT.getAlias(), paasMenuEntity.getAlias())) {
                    throw new XbbException(MarketingErrorCodeEnum.API_ERROR_1500018);
                }
            }
        }
        Map<Long, PaasMenuEntity> menuMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        for (PaasMenuEntity item : menuList) {
            menuMap.put(item.getId(), item);
        }
        List<CompanyConfigAddDTO> userConfigAddDTOList = new ArrayList<>();
        if (Objects.nonNull(commonFormList)) {
            CompanyConfigAddDTO commonForm = new CompanyConfigAddDTO();
            commonForm.setConfigAlias(UserConfigEnum.COMMON_FORM.getAlias());
            commonForm.setConfigName(UserConfigEnum.COMMON_FORM.getName());
            List<MenuReturnPojo> menuReturnList = new ArrayList<>();
            for (int i = 0; i < commonFormList.size(); i++) {
                PaasMenuEntity paasMenuEntity = menuMap.get(commonFormList.get(i));
                MenuReturnPojo menuReturnPojo = new MenuReturnPojo();
                BeanUtil.copyProperties(paasMenuEntity, menuReturnPojo);
                menuReturnPojo.setMenuId(paasMenuEntity.getId());
                menuReturnPojo.setSort(i);
                menuReturnList.add(menuReturnPojo);
            }
            commonForm.setConfigValue(JSON.toJSONString(menuReturnList));
            userConfigAddDTOList.add(commonForm);
        }
        if (Objects.nonNull(quickNewList)) {
            CompanyConfigAddDTO quickNewForm = new CompanyConfigAddDTO();
            quickNewForm.setConfigAlias(UserConfigEnum.QUICK_NEW_FORM.getAlias() + "_" + platForm);
            quickNewForm.setConfigName(UserConfigEnum.QUICK_NEW_FORM.getName());
            List<MenuReturnPojo> menuReturnList = new ArrayList<>();
            for (int i = 0; i < quickNewList.size(); i++) {
                PaasMenuEntity paasMenuEntity = menuMap.get(quickNewList.get(i));
                MenuReturnPojo menuReturnPojo = new MenuReturnPojo();
                BeanUtil.copyProperties(paasMenuEntity, menuReturnPojo);
                menuReturnPojo.setMenuId(paasMenuEntity.getId());
                menuReturnPojo.setSort(i);
                menuReturnList.add(menuReturnPojo);
            }
            quickNewForm.setConfigValue(JSON.toJSONString(menuReturnList));
            userConfigAddDTOList.add(quickNewForm);
        }
        return userConfigAddDTOList;
    }

    @Override
    public ControlCenterMenuListVO controlCenterMenuList(ControlCenterMenuListDTO controlCenterMenuListDTO) throws XbbException {
        ControlCenterMenuListVO controlCenterMenuListVO = new ControlCenterMenuListVO();
        UserVO loginUser = controlCenterMenuListDTO.getLoginUser();
        if (loginUser == null) {
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100004);
        }
        String corpid = controlCenterMenuListDTO.getCorpid();
        try {
            //**********************获取应用信息*********************************SATRT
            Map<String, Object> param = BeanUtil.convertBean2Map(controlCenterMenuListDTO);
            param.put("enable", 1);
//            param.put("aliasNotIn", Arrays.asList(SystemAppMenuEnum.EXPENSE_MANAGEMENT.getAlias(),
//                    SystemAppMenuEnum.ESIGN.getAlias()));
            param.put("aliasNotIn", Arrays.asList(SystemAppMenuEnum.EXPENSE_MANAGEMENT.getAlias(), SystemAppMenuEnum.BUNDLE.getAlias()));
            param.put("orderByStr", "sort ASC");
            List<PaasAppEntity> appList = paasAppModel.list(param);
            if (Objects.isNull(appList)) {
                appList = new ArrayList<>();
            }
            Map<String, PaasAppEntity> appMap = new HashMap<>(appList.size());
            for (PaasAppEntity entity : appList) {
                if (StringUtil.isEmpty(entity.getAlias())) {
                    continue;
                }
                appMap.put(entity.getAlias(), entity);
            }
            //**********************获取应用信息**********************************END

            List<ControlCenterMenuVO> controlCenterMenuList = new ArrayList<>();
            List<ControlCenterMenuVO> applicationManagementList = new ArrayList<>();

            SearchCustomerCompanyEntity soukeEntity = searchCustomerCompanyModel.getByCorpid(loginUser.getCorpid(), SoukeMealEnum.SOUKE.getType());
            FineClueCompanyEntity fineClueEntity = fineClueCompanyModel.getByCorpid(corpid, FineClueEnum.FINE_CLUE.getType());


            //******************************获取权限信息*************************START
            Set<String> permissionSet = loginUser.getPermSet();
//            String s = JSONObject.toJSONString(permissionSet);
            Boolean isAdminOrBoss = loginUser.isAdminOrBoss();

            // 是否有智能助手菜单
            boolean hasAssistantMenu = false;
            boolean hasAssistantPerm = controlCenterMenuListDTO.getLoginUser().getPermSet().contains(ProPermissionAliasEnum.AI_ASSISTANT.getAlias());
            if (hasAssistantPerm) {
                hasAssistantMenu = smartSettingsHelp.hasMenu(controlCenterMenuListDTO.getCorpid());
            }
            // 套餐类型
            Integer feeType = packageHelp.getFeeType(corpid);
            // 是否有数据中心菜单（数据中心的权限和图表中心的编辑权限）
            boolean hasDataCenterPerm = controlCenterMenuListDTO.getLoginUser().getPermSet().contains(ProPermissionAliasEnum.DATA_CENTER.getAlias())
                    && Objects.equals(feeType, PackageTypeEnum.ULTIMATE.getType());
            // 是否有页面定制
            boolean hasCustomPage = (controlCenterMenuListDTO.getLoginUser().getPermSet().contains(ProPermissionAliasEnum.CUSTOM_PAGE.getAlias()) ||
                    controlCenterMenuListDTO.getLoginUser().getPermSet().contains(ProPermissionAliasEnum.MENU_SET_VIEW.getAlias()) ||
                    controlCenterMenuListDTO.getLoginUser().getPermSet().contains(ProPermissionAliasEnum.MENU_SET_UPDATE.getAlias()));
            BasePackageInfoVO basePackageInfoVO = packageService.getBasePackageInfoFromRedis(corpid);

            // 是否启用价目表
            boolean hasPriceSetMenu = false;
            CompanyConfigEntity priceConfigEntity = companyConfigModel.getByConfigAlias(CompanyConfigEnum.PRICE_MANAGE.getAlias(), controlCenterMenuListDTO.getCorpid());
            if (priceConfigEntity != null) {
                hasPriceSetMenu = Objects.equals(priceConfigEntity.getConfigValue(), "1");
            }
            boolean hasPriceSetPerm = controlCenterMenuListDTO.getLoginUser().getPermSet().contains(ProPermissionAliasEnum.PRICE_LIST_SET.getAlias());
            // 是否启用物流查询
            boolean hasExpressSearch = false;
            CompanyConfigEntity expressConfigEntity = companyConfigModel.getByConfigAlias(CompanyConfigEnum.LOGISTICS_TRACKING.getAlias(), controlCenterMenuListDTO.getCorpid());
            if (expressConfigEntity != null) {
                hasExpressSearch = Objects.equals(expressConfigEntity.getConfigValue(), "1");
            }
            // 是否启用电子面单
            boolean hasElectronicSheet = false;
            CompanyConfigEntity electronicSheetConfigEntity = companyConfigModel.getByConfigAlias(CompanyConfigEnum.ELECTRONIC_FACE_SHEET.getAlias(), controlCenterMenuListDTO.getCorpid());
            if (electronicSheetConfigEntity != null) {
                hasElectronicSheet = Objects.equals(electronicSheetConfigEntity.getConfigValue(), "1");
            }
            //是否启用营销
            boolean hasMarketing = false;
            PaasAppEntity appEntity = paasAppModel.getByAlias(XbbRefTypeEnum.MARKETING_MANAGEMENT.getAlias(), corpid);
            if (appEntity != null) {
                hasMarketing = Objects.equals(appEntity.getEnable(), 1);
            }
            Boolean pastDue = feeLogService.workOrderV2PastDue(corpid);
            if (pastDue) {
                appList.removeIf(app -> Objects.equals(XbbRefTypeEnum.WORK_ORDER_V2_CENTER.getAlias(), app.getAlias()));
            }
            //非旗舰版暂时不展示数据集
            boolean unUltimate = !Objects.equals(feeType, PackageTypeEnum.ULTIMATE.getType());
            // 是否开启wps在线编辑器
            boolean isOpenOnlineEditor = commonHelp.isOpenOnlineEditor(corpid);

            for(ControlCenterMenuEnum controlCenterMenuEnum: ControlCenterMenuEnum.values()){
                String alias = controlCenterMenuEnum.getAlias();
                String permissionAlias = controlCenterMenuEnum.getAlias();
                if (ControlCenterMenuEnum.WORK_FLOW.getAlias().equals(controlCenterMenuEnum.getAlias())) {
                    permissionAlias = ProPermissionAliasEnum.PROCESS_SET.getAlias();
                }
                //权限判断
                if (!isAdminOrBoss && !permissionSet.contains(permissionAlias)) {
                    continue;
                }
                if (unUltimate && Objects.equals(alias, ControlCenterMenuEnum.DATA_SET.getAlias())) {
                    continue;
                }
                // 在钉钉环境里面，如果当前为标准版，则不显示知识库标签
                if (Objects.equals(alias, ControlCenterMenuEnum.TAG_SET.getAlias())) {
                    CompanyEntity companyEntity = companyModel.getByKey(corpid);
                    Integer source = companyEntity.getSource();
                    if (Objects.equals(source, 1) && Objects.equals(feeType, PackageTypeEnum.STANDARD.getType())) {
                        continue;
                    }
                }
                // 合同比对试用版不展示菜单
                if (Objects.equals(alias, ControlCenterMenuEnum.CONTRACT_COMPARE.getAlias())) {
                    Integer compareStatus = contractCompareUtil.getContractCompareStatus(corpid);
                    PaasAppEntity paasAppEntity = paasAppModel.getByAlias(ControlCenterMenuEnum.CONTRACT_COMPARE.getAlias(), corpid);
                    if (Objects.isNull(paasAppEntity) || Objects.equals(compareStatus, ContractCompareFeeStatusEnum.TRIAL.getType()) || Objects.equals(paasAppEntity.getEnable(), BasicConstant.ZERO)) {
                        continue;
                    }
                }

                //1为精线索的搜客，2为老的搜客，3啥也没有
                Integer searchMark = 3;
                if (Objects.equals(alias, ControlCenterMenuEnum.SEARCH_CUSTOMER.getAlias())) {
                    //老搜客与新搜客都不存在才不继续走
                    //判断精线索是否可用
                    FineClueCompanyEntity fineClueCompanyEntity = fineClueCompanyModel.getByCorpid(loginUser.getCorpid(), FineClueEnum.FINE_CLUE.getType());
                    boolean b = fineClueCompanyEntity == null || fineClueCompanyEntity.getExtraExpiry() <= DateUtil.getInt();
                    if (!b) {
                        searchMark = 1;
                    }
                    // 搜客过期不给展示，搜客试用也不给展示,而且
                    boolean searchBool = Objects.equals(alias, ControlCenterMenuEnum.SEARCH_CUSTOMER.getAlias()) && (soukeEntity == null || soukeEntity.getExtraExpiry() <= DateUtil.getInt()
                            || soukeEntity.getExtraExpiry() - soukeEntity.getAddTime() < 4 * RedisConstant.LONG_DURATION);
                    if (!searchBool) {
                        searchMark = 2;
                    }
                    //如果两个都没开通则结束
                    if (searchBool && b) {
                        continue;
                    }
                }

                if (Objects.equals(alias, ControlCenterMenuEnum.DATA_CONNECTION.getAlias())) {
                    if (dataConnectionService.tplusEnable(corpid)) {
                        controlCenterMenuList.add(dataConnectionService.getDataConnectionMenu());
                    }
                    continue;
                }

                // 精线索的搜客过期不展示
                if (Objects.equals(alias, ControlCenterMenuEnum.FINE_CLUE.getAlias()) && (fineClueEntity == null || fineClueEntity.getExtraExpiry() <= DateUtil.getInt())) {
                    continue;
                }
                // 智能助手
                if (Objects.equals(ProPermissionAliasEnum.AI_ASSISTANT.getAlias(), alias) && !hasAssistantMenu) {
                    // 标准版 or 有白名单且不在白名中单不展示
                    continue;
                }
                if (!Objects.equals(PackageTypeEnum.ULTIMATE.getType(), basePackageInfoVO.getFeeType()) && ControlCenterMenuEnum.getLowCodeList().contains(alias)) {
                    continue;
                }
                if (!commonHelp.isOpenWorkFlow(corpid) && ControlCenterMenuEnum.WORK_FLOW.getAlias().equals(controlCenterMenuEnum.getAlias())) {
                    continue;
                } else if (commonHelp.isOpenWorkFlow(corpid) && ControlCenterMenuEnum.PROCESS_SETTINGS.getAlias().equals(controlCenterMenuEnum.getAlias())) {
                    continue;
                }

                // 数据中心
                if (Objects.equals(ProPermissionAliasEnum.DATA_CENTER.getAlias(), alias) && !hasDataCenterPerm) {
                    continue;
                }
                // 页面定制
                if (Objects.equals(ProPermissionAliasEnum.CUSTOM_PAGE.getAlias(), alias) && !hasCustomPage) {
                    continue;
                }
                // wps在线编辑
                if (Objects.equals(ControlCenterMenuEnum.CONTRACT_MANAGE.getAlias(), alias) && !isOpenOnlineEditor) {
                    continue;
                }


                ControlCenterMenuVO controlCenterMenuVO = new ControlCenterMenuVO();
                controlCenterMenuVO.setAlias(controlCenterMenuEnum.getAlias());
                controlCenterMenuVO.setName(controlCenterMenuEnum.getName());
                controlCenterMenuVO.setIcon(controlCenterMenuEnum.getIcon());
                controlCenterMenuVO.setUrl(controlCenterMenuEnum.getUrl());
                ControlCenterMenuEnum controlCenterMenu = ControlCenterMenuEnum.getControlCenterMenuEnum(alias);
                switch (controlCenterMenu) {
                    case FORM_TEMPLATE:
                        List<PaasAppMenuVO> formAppList = getControlCenterSubMenuList(appList, ControlCenterMenuEnum.FORM_TEMPLATE, 0);
                        controlCenterMenuVO.setSubMenuList(formAppList);
                        break;
                    case PROCESS_SETTINGS:
                        List<PaasAppMenuVO> processFormAppList = getControlCenterSubMenuList(appList, ControlCenterMenuEnum.PROCESS_SETTINGS, 0);
                        controlCenterMenuVO.setSubMenuList(processFormAppList);
                        break;
                    case ORGANIZATION_AUTHORITY:
                        List<PaasAppMenuVO> list = new ArrayList<>();
                        for (OrganizationAuthorityEnum organizationAuthorityEnum : OrganizationAuthorityEnum.values()) {
                            if (Objects.equals(organizationAuthorityEnum.getPermission(), ProPermissionAliasEnum.SHARE_PERMISSION.getAlias())
                                    && (unUltimate || !sharePermissionHelp.checkSharePermissionWhite(corpid))) {
                                continue;
                            }
                            if (!isAdminOrBoss && !permissionSet.contains(organizationAuthorityEnum.getPermission())) {
                                continue;
                            }
                            PaasAppMenuVO paasAppMenuVO = new PaasAppMenuVO();
                            paasAppMenuVO.setName(organizationAuthorityEnum.getName());
                            paasAppMenuVO.setIcon(organizationAuthorityEnum.getAccessLinkEnum().getIcon());
                            paasAppMenuVO.setUrl(organizationAuthorityEnum.getAccessLinkEnum().getUrl());
                            list.add(paasAppMenuVO);
                        }
                        if (CollectionsUtil.isEmpty(list)) {
                            continue;
                        }
                        controlCenterMenuVO.setSubMenuList(list);
                        break;
                    case MESSAGE_PUSH:
                        List<PaasAppMenuVO> messageList = getControlCenterSubMenuList(appList, ControlCenterMenuEnum.MESSAGE_PUSH, 1);
                        if (pastDue) {
                            messageList.removeIf(meun -> Objects.equals(meun.getAlias(), XbbRefTypeEnum.WORK_ORDER_V2_CENTER.getAlias()));
                        }
                        controlCenterMenuVO.setSubMenuList(messageList);
                        break;
                    case PRINT_TEMPLATE:
                        List<PaasAppMenuVO> printTemplateList = getControlCenterSubMenuList(appList, ControlCenterMenuEnum.PRINT_TEMPLATE, 0);
                        controlCenterMenuVO.setSubMenuList(printTemplateList);
                        break;
                    case WORK_ORDER:
                        PaasAppEntity paasAppEntity = appMap.get(XbbRefTypeEnum.WORK_ORDER.getAlias());
                        if (Objects.isNull(paasAppEntity) || Objects.equals(paasAppEntity.getEnable(), 0)) {
                            continue;
                        }
                        List<PaasAppMenuVO> workOrderCenterList = new ArrayList<>();
                        for (WorkOrderControlCenterEnum workOrderControlCenterEnum : WorkOrderControlCenterEnum.values()) {
                            if (isAdminOrBoss || permissionSet.contains(workOrderControlCenterEnum.getPermission())) {
                                PaasAppMenuVO paasAppMenuVO = new PaasAppMenuVO();
                                paasAppMenuVO.setId(paasAppEntity.getId());
                                paasAppMenuVO.setName(workOrderControlCenterEnum.getName());
                                paasAppMenuVO.setIcon(workOrderControlCenterEnum.getIcon());
                                paasAppMenuVO.setUrl(workOrderControlCenterEnum.getUrl() + "?appId=" + paasAppEntity.getId());
                                workOrderCenterList.add(paasAppMenuVO);
                            }
                        }
                        if (workOrderCenterList.isEmpty()) {
                            continue;
                        }
                        controlCenterMenuVO.setSubMenuList(workOrderCenterList);
                        break;
                    case CALL_CENTER:
                        Boolean enableXbb = Objects.isNull(appMap.get(XbbRefTypeEnum.CALL_CENTER_XBB.getAlias()))
                                || Objects.equals(appMap.get(XbbRefTypeEnum.CALL_CENTER_XBB.getAlias()).getEnable(), 0);
                        Boolean enableDuYan = Objects.isNull(appMap.get(XbbRefTypeEnum.CALL_CENTER_DU_YAN.getAlias()))
                                || Objects.equals(appMap.get(XbbRefTypeEnum.CALL_CENTER_DU_YAN.getAlias()).getEnable(), 0);
                        if (enableXbb && enableDuYan) {
                            continue;
                        }
                        List<PaasAppMenuVO> callCenterList = new ArrayList<>();
                        for (CallCenterEnum callCenterEnum : CallCenterEnum.values()) {
                            PaasAppMenuVO paasAppMenuVO = new PaasAppMenuVO();
                            paasAppMenuVO.setName(callCenterEnum.getName());
                            paasAppMenuVO.setIcon(callCenterEnum.getIcon());
                            paasAppMenuVO.setUrl(callCenterEnum.getUrl());
                            callCenterList.add(paasAppMenuVO);
                        }
                        controlCenterMenuVO.setSubMenuList(callCenterList);
                        break;
                    case GROUP_MESSAGE:
                        Boolean enableMessage = Objects.isNull(appMap.get(XbbRefTypeEnum.GROUP_MESSAGE.getAlias()))
                                || Objects.equals(appMap.get(XbbRefTypeEnum.GROUP_MESSAGE.getAlias()).getEnable(), 0);
                        if (enableMessage) {
                            continue;
                        }
                        List<PaasAppMenuVO> groupMessageList = new ArrayList<>();
                        for (GroupMessageMenuEnum groupMessageMenuEnum : GroupMessageMenuEnum.values()) {
                            if (PaasConstant.HOME_STRING.equals(groupMessageMenuEnum.getBelong())) {
                                continue;
                            }
                            if (!isAdminOrBoss && !permissionSet.contains(groupMessageMenuEnum.getPermission())) {
                                continue;
                            }
                            PaasAppMenuVO paasAppMenuVO = new PaasAppMenuVO();
                            paasAppMenuVO.setName(groupMessageMenuEnum.getName());
                            paasAppMenuVO.setIcon(groupMessageMenuEnum.getAccessLinkEnum().getIcon());
                            paasAppMenuVO.setUrl(groupMessageMenuEnum.getAccessLinkEnum().getUrl());
                            groupMessageList.add(paasAppMenuVO);
                        }
                        controlCenterMenuVO.setSubMenuList(groupMessageList);
                        break;
                    case ESIGN:
                        Boolean enableEsign = Objects.isNull(appMap.get(XbbRefTypeEnum.ESIGN.getAlias()))
                                || Objects.equals(appMap.get(XbbRefTypeEnum.ESIGN.getAlias()).getEnable(), 0);
                        if (enableEsign) {
                            continue;
                        }
                        List<PaasAppMenuVO> esignList = new ArrayList<>();
                        for (EsignMenuEnum esignMenuEnum : EsignMenuEnum.values()) {
                            if (PaasConstant.HOME_STRING.equals(esignMenuEnum.getBelong())) {
                                continue;
                            }
                            if (!isAdminOrBoss && !permissionSet.contains(esignMenuEnum.getPermission())) {
                                continue;
                            }
                            PaasAppMenuVO paasAppMenuVO = new PaasAppMenuVO();
                            paasAppMenuVO.setName(esignMenuEnum.getName());
                            paasAppMenuVO.setIcon(esignMenuEnum.getAccessLinkEnum().getIcon());
                            paasAppMenuVO.setUrl(esignMenuEnum.getAccessLinkEnum().getUrl());
                            esignList.add(paasAppMenuVO);
                        }
                        controlCenterMenuVO.setSubMenuList(esignList);
                        break;
                    case SEARCH_CUSTOMER:
                        boolean enableSearch = Objects.isNull(appMap.get(XbbRefTypeEnum.SEARCH_CUSTOMER.getAlias()))
                                || Objects.equals(appMap.get(XbbRefTypeEnum.SEARCH_CUSTOMER.getAlias()).getEnable(), 0);
                        if (enableSearch) {
                            continue;
                        }
                        if (Objects.equals(searchMark, 1)) {
                            List<PaasAppMenuVO> fineMenuList = new ArrayList<>();
                            for (FineClueMenuEnum fineClueMenuEnum : FineClueMenuEnum.values()) {
                                if (PaasConstant.HOME_STRING.equals(fineClueMenuEnum.getBelong())) {
                                    continue;
                                }
                                if (!permissionSet.contains(ProPermissionAliasEnum.SOUKE_VIEW.getAlias())) {
                                    continue;
                                }
                                PaasAppMenuVO paasAppMenuVO = new PaasAppMenuVO();
                                paasAppMenuVO.setName(fineClueMenuEnum.getName());
                                paasAppMenuVO.setIcon(fineClueMenuEnum.getAccessLinkEnum().getIcon());
                                paasAppMenuVO.setUrl(fineClueMenuEnum.getAccessLinkEnum().getUrl());
                                fineMenuList.add(paasAppMenuVO);
                            }
                            controlCenterMenuVO.setSubMenuList(fineMenuList);
                            //管理中心点击搜客进入精线索坐席
//                            controlCenterMenuVO.setAlias("fineCluePermission");
                        } else if (Objects.equals(searchMark, 2)) {
                            List<PaasAppMenuVO> searchMenuList = new ArrayList<>();
                            for (SearchCustomerMenuEnum searchCustomerMenuEnum : SearchCustomerMenuEnum.values()) {
                                if (PaasConstant.HOME_STRING.equals(searchCustomerMenuEnum.getBelong())) {
                                    continue;
                                }
                                if (!permissionSet.contains(ProPermissionAliasEnum.SOUKE_VIEW.getAlias())) {
                                    continue;
                                }
                                PaasAppMenuVO paasAppMenuVO = new PaasAppMenuVO();
                                paasAppMenuVO.setName(searchCustomerMenuEnum.getName());
                                paasAppMenuVO.setIcon(searchCustomerMenuEnum.getAccessLinkEnum().getIcon());
                                paasAppMenuVO.setUrl(searchCustomerMenuEnum.getAccessLinkEnum().getUrl());
                                searchMenuList.add(paasAppMenuVO);
                            }
                            controlCenterMenuVO.setSubMenuList(searchMenuList);
                        }
                        break;
                    case FINE_CLUE:
                        boolean enableFine = Objects.isNull(appMap.get(XbbRefTypeEnum.FINE_CLUE.getAlias()))
                                || Objects.equals(appMap.get(XbbRefTypeEnum.FINE_CLUE.getAlias()).getEnable(), 0);
                        if (enableFine) {
                            continue;
                        }
                        List<PaasAppMenuVO> fineMenuList = new ArrayList<>();
                        for (FineClueMenuEnum fineClueMenuEnum : FineClueMenuEnum.values()) {
                            if (PaasConstant.HOME_STRING.equals(fineClueMenuEnum.getBelong())) {
                                continue;
                            }
                            if (!permissionSet.contains(ProPermissionAliasEnum.FINE_CLUE_VIEW.getAlias())) {
                                continue;
                            }
                            PaasAppMenuVO paasAppMenuVO = new PaasAppMenuVO();
                            paasAppMenuVO.setName(fineClueMenuEnum.getName());
                            paasAppMenuVO.setIcon(fineClueMenuEnum.getAccessLinkEnum().getIcon());
                            paasAppMenuVO.setUrl(fineClueMenuEnum.getAccessLinkEnum().getUrl());
                            fineMenuList.add(paasAppMenuVO);
                        }
                        controlCenterMenuVO.setSubMenuList(fineMenuList);
                        break;
                    case OTHER_SETTINGS:
                        boolean noEnableJxc = Objects.isNull(appMap.get(XbbRefTypeEnum.JXC.getAlias()));
                        List<PaasAppMenuVO> otherSetList = new ArrayList<>();
                        List<AppMenuListVO> jxcSetList = new ArrayList<>();
                        for (OtherSetEnum otherSetEnum : OtherSetEnum.values()) {
                            if (!isAdminOrBoss && !permissionSet.contains(otherSetEnum.getPermission()) && StringUtil.isNotEmpty(otherSetEnum.getPermission())) {
                                continue;
                            }
                            if (noEnableJxc && OtherSetEnum.JXC_SETTINGS.equals(otherSetEnum)) {
                                continue;
                            }
                            if (!hasMarketing && OtherSetEnum.MARKETING_MANAGEMENT.equals(otherSetEnum)) {
                                continue;
                            }
                            if (OtherSetEnum.PRICE_LIST_SETTINGS.equals(otherSetEnum) && !(hasPriceSetMenu && hasPriceSetPerm)) {
                                continue;
                            }
                            if (OtherSetEnum.LOGISTICS_QUERY.equals(otherSetEnum) && !hasExpressSearch) {
                                continue;
                            }
                            if (OtherSetEnum.ELECTRONIC_SURFACE_SINGLE_SETTINGS.equals(otherSetEnum) && !hasElectronicSheet) {
                                continue;
                            }
                            if (Objects.equals(OtherSetEnum.PUBLIC_CLUE_SEA_POOL, otherSetEnum)) {
                                //高级版和旗舰版，并且开启了市场管理才可
                                Boolean standardWithFeeType = marketManagementBusinessHelp.isStandardWithFeeType(corpid);
                                if (standardWithFeeType) {
                                    continue;
                                }
                                boolean enableWithApp = marketManagementBusinessHelp.isEnableWithApp(corpid);
                                if (!enableWithApp) {
                                    continue;
                                }
                            }
                            if (Objects.equals(otherSetEnum, OtherSetEnum.GLOBAL_WATERMARK)) {
                                otherSetList.add(waterMarkService.getWaterMarkMenu());
                                continue;
                            }
                            PaasAppMenuVO paasAppMenuVO = new PaasAppMenuVO();
                            paasAppMenuVO.setName(otherSetEnum.getName());
                            paasAppMenuVO.setIcon(otherSetEnum.getAccessLinkEnum().getIcon());
                            paasAppMenuVO.setUrl(otherSetEnum.getAccessLinkEnum().getUrl());
                            if (OtherSetEnum.JXC_SETTINGS.equals(otherSetEnum) && !noEnableJxc) {
                                paasAppMenuVO.setSubMenuList(jxcSetList);
                            }
                            otherSetList.add(paasAppMenuVO);
                        }
                        if (otherSetList.isEmpty()) {
                            continue;
                        }
                        controlCenterMenuVO.setSubMenuList(otherSetList);
                        break;
                    case CUSTOM_PAGE:
                        list = new ArrayList<>();
                        for (CustomPageMenuEnum customPageMenuEnum : CustomPageMenuEnum.values()) {
                            if (Objects.equals(customPageMenuEnum, CustomPageMenuEnum.MENU_SETTINGS)) {
                                if (!permissionSet.contains(customPageMenuEnum.getPermission()) && !permissionSet.contains(ProPermissionAliasEnum.MENU_SET_UPDATE.getAlias())) {
                                    continue;
                                }
                            } else {
                                if (Objects.equals(customPageMenuEnum, CustomPageMenuEnum.HOME_PAGE_MANAGEMENT) && !Objects.equals(feeType, PackageTypeEnum.ULTIMATE.getType())) {
                                    continue;
                                }
                                if (!permissionSet.contains(customPageMenuEnum.getPermission())) {
                                    continue;
                                }
                            }
                            PaasAppMenuVO paasAppMenuVO = new PaasAppMenuVO();
                            paasAppMenuVO.setName(customPageMenuEnum.getName());
                            paasAppMenuVO.setIcon(customPageMenuEnum.getIcon());
                            paasAppMenuVO.setUrl(customPageMenuEnum.getUrl());
                            list.add(paasAppMenuVO);
                        }
                        if (CollectionsUtil.isEmpty(list)) {
                            continue;
                        }
                        controlCenterMenuVO.setSubMenuList(list);
                        break;
                    case WORK_ORDER_V2_CENTER:
                        PaasAppEntity paasApp = appMap.get(XbbRefTypeEnum.WORK_ORDER_V2_CENTER.getAlias());
                        if (Objects.isNull(paasApp) || Objects.equals(paasApp.getEnable(), 0) || pastDue) {
                            continue;
                        }
                        List<PaasAppMenuVO> workOrderV2CenterList = new ArrayList<>();
                        for (WorkOrderV2CenterEnum workOrderControlCenterEnum : WorkOrderV2CenterEnum.values()) {
                            if (isAdminOrBoss || permissionSet.contains(workOrderControlCenterEnum.getPermission())) {
                                PaasAppMenuVO paasAppMenuVO = new PaasAppMenuVO();
                                paasAppMenuVO.setName(workOrderControlCenterEnum.getName());
                                paasAppMenuVO.setIcon(workOrderControlCenterEnum.getIcon());
                                paasAppMenuVO.setUrl(workOrderControlCenterEnum.getUrl());
                                workOrderV2CenterList.add(paasAppMenuVO);
                            }
                        }
                        if (workOrderV2CenterList.isEmpty()) {
                            continue;
                        }
                        controlCenterMenuVO.setSubMenuList(workOrderV2CenterList);
                        break;
                    case CONTRACT_COMPARE:
                        // 合同比对坐席管理页
                        controlCenterMenuVO.setUrl(AccessLinkEnum.CONTRACT_COMPARE_MANAGE.getUrl());
                        controlCenterMenuVO.setIcon(AccessLinkEnum.CONTRACT_COMPARE.getIcon());
                        break;
                    case CONTRACT_MANAGE:
                        // wps在线编辑 合同管理
                        List<PaasAppMenuVO> contractManageCenterList = new ArrayList<>();
                        for (ContractManegeCenterEnum temp : ContractManegeCenterEnum.values()) {
                            if (isAdminOrBoss || permissionSet.contains(temp.getPermission())) {
                                PaasAppMenuVO paasAppMenuVO = new PaasAppMenuVO();
                                paasAppMenuVO.setName(temp.getName());
                                paasAppMenuVO.setIcon(temp.getIcon());
                                paasAppMenuVO.setUrl(temp.getUrl());
                                contractManageCenterList.add(paasAppMenuVO);
                            }
                        }
                        if (contractManageCenterList.isEmpty()) {
                            continue;
                        }
                        controlCenterMenuVO.setSubMenuList(contractManageCenterList);
                        break;
                    default:
                        break;
                }
                if (ControlCenterMenuEnum.APPLICATION_MANAGEMENT.getAlias().equals(controlCenterMenuEnum.getAlias())) {
                    applicationManagementList.add(controlCenterMenuVO);
                } else {
                    controlCenterMenuList.add(controlCenterMenuVO);
                }

            }
            // 判断是否有阿里云呼叫中心权限
            IsActiveAliyunCallVO activeAliyunCall1 = callCenterCommonService.isActiveAliyunCall(corpid, controlCenterMenuListDTO.getUserId());
            if (Objects.nonNull(activeAliyunCall1) && activeAliyunCall1.isActiveAliyunCall()) {
                ControlCenterMenuVO menuList = callCenterCommonService.getManagementCenterMenuList(controlCenterMenuListDTO.getPlatform(), activeAliyunCall1.getRole(), activeAliyunCall1.getFacilitators());
                if (Objects.nonNull(menuList)) {
                    controlCenterMenuList.add(menuList);
                }
            }
            //判断是否有AI中心权限
            IsActiveAIComboVO isActiveAIComboVO = isActiveAICombo(corpid, loginUser, controlCenterMenuListDTO.getPlatform(), isAdminOrBoss);
            if (Objects.nonNull(isActiveAIComboVO) && isActiveAIComboVO.getIsExpired()) {
                ControlCenterMenuVO menuList = getAICenterMenuList(controlCenterMenuListDTO.getPlatform());
                if (Objects.nonNull(menuList)) {
                    controlCenterMenuList.add(menuList);
                }
            }
            controlCenterMenuListVO.setMenuList(controlCenterMenuList);
            controlCenterMenuListVO.setApplicationManagementList(applicationManagementList);
        } catch (XbbException e) {
            throw e;
        } catch (Exception e) {
            LOG.error("menuService.controlCenterMenuList获取控制中心菜单列表出错：", e);
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, SystemErrorCodeEnum.API_ERROR_100001.getMsg());
        }
        return controlCenterMenuListVO;
    }

    @Override
    public ControlCenterMenuSetListVO controlCenterMenuSetList(ControlCenterMenuSetListDTO controlCenterMenuSetListDTO) throws XbbException {
        ControlCenterMenuSetListVO controlCenterMenuSetListVO = new ControlCenterMenuSetListVO();
        try {
            String corpid = controlCenterMenuSetListDTO.getCorpid();
            Map<String, Object> param = BeanUtil.convertBean2Map(controlCenterMenuSetListDTO, true);
            param.put("orderByStr", "enable DESC, sort ASC, update_time ASC");
            List<PaasAppEntity> appList = paasAppModel.list(param);
            if (Objects.isNull(appList)) {
                appList = new ArrayList<>();
            }
            Boolean pastDue = feeLogService.workOrderV2PastDue(controlCenterMenuSetListDTO.getCorpid());
            if (pastDue) {
                appList.removeIf(app -> Objects.equals(XbbRefTypeEnum.WORK_ORDER_V2_CENTER.getAlias(), app.getAlias()));
            }
            MenuNewListDTO menuNewListDTO = new MenuNewListDTO();
            BeanUtil.copyProperties(controlCenterMenuSetListDTO, menuNewListDTO, false);
            MenuNewListVO menuNewListVO = new MenuNewListVO();
            List<AppMenuListVO> commonFormList = new ArrayList<>();
            // 将菜单列表分应用存放到容器中
            MenuConfigPojo menuConfigPojo = new MenuConfigPojo();
            menuConfigPojo.setSearchSelfConfig(false);
            menuConfigPojo.setSearchCompanyConfig(true);
            menuConfigPojo.setPermissionFlag(false);
            menuConfigPojo.setIsHomeList(2);
            List<String> featureList = packageHelp.getFeatureList(menuNewListDTO.getCorpid());
            Integer num = updatePackageRedisService.getUnusedNumPackageLimit(menuNewListDTO.getCorpid(), ValueAddedTypeEnum.CUSTOM_FORM_NUM);
            Map<Long, List<AppMenuListVO>> menuListMap = proMenuHelp.getMenuList(menuNewListDTO, menuNewListVO, commonFormList, new ArrayList<>(),
                    menuConfigPojo, featureList, num);
            List<PaasAppMenuVO> appVOList = new ArrayList<>(appList.size());
            List<PaasAppMenuVO> selfBuiltAppList = new ArrayList<>();

            appList.forEach((item) -> {
                PaasAppMenuVO paasAppMenuVO = new PaasAppMenuVO();
                BeanUtil.copyProperties(item, paasAppMenuVO);
                if (SaasMarkEnum.PAAS.getCode().equals(item.getSaasMark())) {
                    selfBuiltAppList.add(paasAppMenuVO);
                }
                paasAppMenuVO.setSubMenuList(menuListMap.get(item.getId()));
                if (SystemAppMenuEnum.SEARCH_CUSTOMER.getAlias().equals(item.getAlias())) {
                    // 搜客不可以设置常用表单与快捷新建
                    List<AppMenuListVO> subMenuList = paasAppMenuVO.getSubMenuList();
                    if (CollectionUtils.isNotEmpty(subMenuList)) {
                        subMenuList.forEach((appMenuListVO) -> {
                            appMenuListVO.setHasQuickNewFlag(0);
                        });
                    }
                }
                // 精线索不可以设置常用表单与快捷新建
                if (SystemAppMenuEnum.FINE_CLUE.getAlias().equals(item.getAlias())) {
                    List<AppMenuListVO> subMenuList = paasAppMenuVO.getSubMenuList();
                    if (CollectionUtils.isNotEmpty(subMenuList)) {
                        subMenuList.forEach((appMenuListVO) -> {
                            appMenuListVO.setHasQuickNewFlag(0);
                        });
                    }
                }
                if (SystemAppMenuEnum.ESIGN.getAlias().equals(item.getAlias())) {
                    return;
                }
                try {
                    //标准版的套餐是没有“市场管理”的模块的(应用关闭，不影响他在菜单设置那里展示 fix  35049)
                    if (SystemAppMenuEnum.MARKET_MANAGEMENT.getAlias().equals(item.getAlias()) && (marketManagementBusinessHelp.isStandardWithFeeType((controlCenterMenuSetListDTO.getCorpid())))) {
                        return;
                    }
                } catch (Exception e) {
                    LOG.error("controlCenterMenuSetList 异常信息{}", e.getMessage());
                    return;
                }
                appVOList.add(paasAppMenuVO);
            });
            List<Long> commonFormIdList = new ArrayList<>();
            commonFormList.forEach(item -> {
                commonFormIdList.add(item.getId());
            });
            controlCenterMenuSetListVO.setCommonFormList(commonFormIdList);
            List<Long> quickFormList = new ArrayList<>();
            menuNewListVO.getQuickNewList().forEach(item -> {
                quickFormList.add(item.getId());
            });
            //渲染跨应用移动菜单的处理
            if (commonHelp.isOpenMenuWhite(corpid)) {
                proMenuHelp.formatAppMenuVoList(appVOList, corpid);
            }
            controlCenterMenuSetListVO.setQuickNewFormList(quickFormList);
            controlCenterMenuSetListVO.setMenuList(appVOList);
            controlCenterMenuSetListVO.setSelfBuiltAppList(selfBuiltAppList);
            // 国际化白名单
            CompanyConfigEntity entity = companyConfigModel.getByConfigAlias(CompanyConfigEnum.I18N_WHITE.getAlias(), PaasConstant.DEFAULT_DATA_CORPID);
            String value = CompanyConfigEnum.I18N_WHITE.getValue();
            if (Objects.nonNull(entity)) {
                value = entity.getConfigValue();
            }
            List<String> whiteList = JsonHelperUtil.parseArray(value, String.class);
            boolean flag = CollectionsUtil.isNotEmpty(whiteList) && whiteList.contains(controlCenterMenuSetListDTO.getCorpid());
            controlCenterMenuSetListVO.setMultiLang(flag);
        } catch (XbbException e) {
            throw e;
        } catch (Exception e) {
            LOG.error("menuService.controlCenterMenuSetList管理中心获取菜单列表出错：", e);
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, SystemErrorCodeEnum.API_ERROR_100001.getMsg());
        }
        return controlCenterMenuSetListVO;
    }


    @Override
    public HomeMenuSetListVO homeMenuSetList(HomeMenuSetListDTO homeMenuSetListDTO) throws XbbException {
        HomeMenuSetListVO homeMenuSetListVO = new HomeMenuSetListVO();
        try {
            Map<String, Object> param = BeanUtil.convertBean2Map(homeMenuSetListDTO, true);
            param.put("orderByStr", "enable DESC, sort ASC, update_time ASC");
            List<PaasAppEntity> appList = paasAppModel.list(param);
            if (Objects.isNull(appList)) {
                appList = new ArrayList<>();
            }
            Boolean distributorEnable = paasAppService.validateAppEnable(null, XbbRefTypeEnum.DISTRIBUTOR.getAlias(), SaasMarkEnum.SAAS.getCode(), homeMenuSetListDTO.getCorpid());
            List<String> featureList = packageHelp.getFeatureList(homeMenuSetListDTO.getCorpid());
            MenuNewListDTO menuNewListDTO = new MenuNewListDTO();
            BeanUtil.copyProperties(homeMenuSetListDTO, menuNewListDTO, false);
            MenuNewListVO menuNewListVO = new MenuNewListVO();
            List<AppMenuListVO> commonFormList = new ArrayList<>();
            // 将菜单列表分应用存放到容器中
            MenuConfigPojo menuConfigPojo = new MenuConfigPojo();
            String corpid = menuNewListDTO.getCorpid();
            menuConfigPojo.setSearchSelfConfig(true);
            menuConfigPojo.setSearchCompanyConfig(true);
            menuConfigPojo.setPermissionFlag(true);
            menuConfigPojo.setIsHomeList(2);
            Integer num = updatePackageRedisService.getUnusedNumPackageLimit(corpid, ValueAddedTypeEnum.CUSTOM_FORM_NUM);
            Map<Long, List<AppMenuListVO>> menuListMap = proMenuHelp.getMenuList(menuNewListDTO, menuNewListVO, commonFormList, new ArrayList<>(),
                    menuConfigPojo, featureList, num);
            Boolean pastDue = feeLogService.workOrderV2PastDue(homeMenuSetListDTO.getCorpid());
            List<PaasAppMenuVO> appVOList = new ArrayList<>(appList.size());
            for (PaasAppEntity paasAppEntity : appList) {
                Long appId = paasAppEntity.getId();
                if (Objects.nonNull(menuListMap.get(appId)) && !menuListMap.get(appId).isEmpty()) {
                    PaasAppMenuVO paasAppMenuVO = new PaasAppMenuVO();
                    // 经销商管理关闭时
                    if (!distributorEnable) {
                        if (Objects.equals(paasAppEntity.getAlias(), XbbRefTypeEnum.ORDER_CENTER.getAlias())) {
                            continue;
                        } else if (Objects.equals(paasAppEntity.getAlias(), XbbRefTypeEnum.PRODUCT.getAlias())) {
                            menuListMap.get(appId).removeIf(item -> Objects.equals(item.getAlias(), XbbRefTypeEnum.PRICE_SET_PRODUCT.getAlias()));
                        }
                    }
                    if (SystemAppMenuEnum.WORK_ORDER_V2_CENTER.getAlias().equals(paasAppEntity.getAlias()) && pastDue) {
                        continue;
                    }
                    BeanUtil.copyProperties(paasAppEntity, paasAppMenuVO);
                    paasAppMenuVO.setSubMenuList(menuListMap.get(appId));
                    // 营销管理不在常用表单与快捷新建中展示
                    if (SystemAppMenuEnum.MARKETING_MANAGEMENT.getAlias().equals(paasAppEntity.getAlias())) {
                        continue;
                    }
                    // 搜客不在常用表单与快捷新建中展示
                    if (SystemAppMenuEnum.SEARCH_CUSTOMER.getAlias().equals(paasAppEntity.getAlias())) {
                        continue;
                    }
                    // 精线索不在常用表单与快捷新建中展示
                    if (SystemAppMenuEnum.FINE_CLUE.getAlias().equals(paasAppEntity.getAlias())) {
                        continue;
                    }
                    // 搜客不在常用表单与快捷新建中展示
                    if (SystemAppMenuEnum.ESIGN.getAlias().equals(paasAppEntity.getAlias())) {
                        continue;
                    }
                    //标准版的套餐是没有“市场管理”的模块的
                    if (SystemAppMenuEnum.MARKET_MANAGEMENT.getAlias().equals(paasAppEntity.getAlias()) && (feeTypeIsStandardOrAppIsClosed(homeMenuSetListDTO.getCorpid()))) {
                        continue;
                    }
                    //合同比对不能设置快捷新建
                    if (SystemAppMenuEnum.CONTRACT_COMPARE.getAlias().equals(paasAppEntity.getAlias())) {
                        paasAppMenuVO.getSubMenuList().get(0).setHasQuickNewFlag(0);
                        if (Objects.equals(PlatFormEnum.DINGTALK.getValue(), homeMenuSetListDTO.getPlatform())) {
                            continue;
                        } else if (Objects.equals(PlatFormEnum.WEB.getValue(), homeMenuSetListDTO.getPlatform())) {
                            Integer status = contractCompareUtil.getContractCompareStatus(corpid);
                            // 非试用版
                            if (!Objects.equals(status, ContractCompareFeeStatusEnum.TRIAL.getType())) {
                                Integer compareStaff = contractCompareUtil.getContractCompareStaff(corpid, homeMenuSetListDTO.getUserId());
                                // 坐席未开启，不展示合同比对菜单
                                if (Objects.equals(compareStaff, BasicConstant.ZERO)) {
                                    continue;
                                }
                            }
                        }
                    }
                    appVOList.add(paasAppMenuVO);
                }
            }
            //渲染跨应用移动菜单的处理
            if (commonHelp.isOpenMenuWhite(corpid)) {
                proMenuHelp.formatAppMenuVoList(appVOList, corpid);
            }
            List<Long> commonFormIdList = new ArrayList<>();
            commonFormList.forEach(item -> {
                commonFormIdList.add(item.getId());
            });
            homeMenuSetListVO.setCommonFormList(commonFormIdList);
            List<Long> quickFormList = new ArrayList<>();
            menuNewListVO.getQuickNewList().forEach(item -> {
                quickFormList.add(item.getId());
            });

            homeMenuSetListVO.setQuickNewFormList(quickFormList);
            homeMenuSetListVO.setMenuList(appVOList);
        } catch (XbbException e) {
            throw e;
        } catch (Exception e) {
            LOG.error("menuService.controlCenterMenuSetList管理中心获取菜单列表出错：", e);
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, SystemErrorCodeEnum.API_ERROR_100001.getMsg());
        }
        return homeMenuSetListVO;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ControlCenterMenuSortVO controlCenterMenuSort(ControlCenterMenuSortDTO controlCenterMenuSortDTO) throws XbbException {
        ControlCenterMenuSortVO controlCenterMenuSortVO = new ControlCenterMenuSortVO();
        try {
            List<ApplicationSortPoJo> appList = controlCenterMenuSortDTO.getAppList();
            List<ApplicationSortPoJo> operationAppList = new ArrayList<>(appList.size());
            List<MenuSortPoJo> operationMenuList = new ArrayList<>();
            String corpid = controlCenterMenuSortDTO.getCorpid();
            if (Objects.nonNull(appList)) {
                for (int a = 0; a < appList.size(); a++) {
                    ApplicationSortPoJo item = appList.get(a);
                    ApplicationSortPoJo applicationSortPoJo = new ApplicationSortPoJo();
                    BeanUtil.copyProperties(item, applicationSortPoJo);
                    applicationSortPoJo.setSort(a);
                    operationAppList.add(applicationSortPoJo);
                    List<MenuSortPoJo> menuList = item.getSubMenuList();
                    if (Objects.nonNull(menuList)) {
                        for (int b = 0; b < menuList.size(); b++) {
                            MenuSortPoJo menuItem = menuList.get(b);
                            MenuSortPoJo menuSortPoJo = new MenuSortPoJo();
                            BeanUtil.copyProperties(menuItem, menuSortPoJo);
                            menuSortPoJo.setSort(b);
                            menuSortPoJo.setParentId(0L);
                            operationMenuList.add(menuSortPoJo);
                            List<MenuSortPoJo> subMenuList = menuSortPoJo.getSubMenuList();
                            if (Objects.nonNull(subMenuList)) {
                                for (int c = 0; c < subMenuList.size(); c++) {
                                    MenuSortPoJo subMenuItem = subMenuList.get(c);
                                    MenuSortPoJo subMenuSortPoJo = new MenuSortPoJo();
                                    BeanUtil.copyProperties(subMenuItem, subMenuSortPoJo);
                                    subMenuSortPoJo.setParentId(menuItem.getId());
                                    subMenuSortPoJo.setSort(c);
                                    operationMenuList.add(subMenuSortPoJo);
                                }
                            }
                        }
                    }
                }
            }
            // 应用排序
            ApplicationSortDTO applicationSortDTO = new ApplicationSortDTO();
            BeanUtil.copyProperties(controlCenterMenuSortDTO, applicationSortDTO);
            applicationSortDTO.setAppSort(operationAppList);
            if (!operationAppList.isEmpty()) {
                paasAppService.updateSort(applicationSortDTO);
            }
            // 菜单排序
            MenuSortDTO menuSortDTO = new MenuSortDTO();
            BeanUtil.copyProperties(controlCenterMenuSortDTO, menuSortDTO);
            menuSortDTO.setMenuList(operationMenuList);
            if (!operationMenuList.isEmpty()) {
                sortMenu(menuSortDTO);
            }
            //只对跨应用菜单开启白名单的公司进行保存
            if (commonHelp.isOpenMenuWhite(corpid)) {
                //新的跨应用菜单
                List<CoverPaasMenuEntity> newCoverList = new ArrayList<>();
                //拖回去时需要删除跨应用表中的数据
                List<Long> deleteCoverMenuIds = new ArrayList<>();
                //跨应用菜单数
                List<CoverPaasMenuEntity> allCoverList = coverPaasMenuModel.getList(corpid);
                packageCoverPaasMenuList(newCoverList, deleteCoverMenuIds, controlCenterMenuSortDTO, allCoverList);
                //封装新的AppId
                saveCoverPaasMenuList(newCoverList, deleteCoverMenuIds, corpid, allCoverList);
            }

        } catch (XbbException e) {
            throw e;
        } catch (Exception e) {
            LOG.error("menuService.controlCenterMenuSort应用和菜单排序出错：", e);
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, SystemErrorCodeEnum.API_ERROR_100001.getMsg());
        }
        return controlCenterMenuSortVO;
    }

    /**
     * @param newCoverList             需要更新或者添加的
     * @param deleteCoverMenuIds       需要删除的
     * @param controlCenterMenuSortDTO
     * @param allCoverList             已存在的
     * @return List<CoverPaasMenuEntity>
     * @description 封装需要跨应用的菜单
     * @author yanglei
     * @date 2022/12/12 21:01
     */
    private List<CoverPaasMenuEntity> packageCoverPaasMenuList(List<CoverPaasMenuEntity> newCoverList, List<Long> deleteCoverMenuIds, ControlCenterMenuSortDTO controlCenterMenuSortDTO, List<CoverPaasMenuEntity> allCoverList) {
        List<Long> allCoverIds = new ArrayList<>();
        allCoverList.forEach(item -> allCoverIds.add(item.getMenuId()));
        List<ApplicationSortPoJo> appList = controlCenterMenuSortDTO.getAppList();
        for (ApplicationSortPoJo applicationPoJo : appList) {
            Long newLinkAppId = applicationPoJo.getId();
            //二级菜单列表
            List<MenuSortPoJo> secondMenuList = applicationPoJo.getSubMenuList();
            if (CollectionsUtil.isEmpty(secondMenuList)) {
                continue;
            }
            for (MenuSortPoJo menuSortPoJo : secondMenuList) {
                //证明是跨应用拖动
                if (!Objects.equals(newLinkAppId, menuSortPoJo.getAppId())) {
                    CoverPaasMenuEntity entity = new CoverPaasMenuEntity();
                    entity.setSort(menuSortPoJo.getSort());
                    entity.setMenuId(menuSortPoJo.getId());
                    entity.setCreatorId(controlCenterMenuSortDTO.getUserId());
                    entity.setLinkAppId(newLinkAppId);
                    entity.setCorpid(controlCenterMenuSortDTO.getCorpid());
                    entity.setDel(BasicConstant.ZERO);
                    entity.setAddTime(DateUtil.getNow());
                    entity.setUpdateTime(DateUtil.getNow());
                    newCoverList.add(entity);
                } else {
                    if (allCoverIds.contains(menuSortPoJo.getId())) {
                        deleteCoverMenuIds.add(menuSortPoJo.getId());
                    }
                }
            }
        }
        return newCoverList;
    }


    /**
     * @param newCoverList   包含需要新增的数据和更新的数据
     * @param deleteCoverIds 需要删除的id
     * @param allCoverList   已经保存过的菜单应用关系表
     * @description 跨应用拖拽二级菜单的关系表保存
     * @author yanglei
     * @date 2022/12/2 13:58
     */
    public void saveCoverPaasMenuList(List<CoverPaasMenuEntity> newCoverList, List<Long> deleteCoverIds, String corpid, List<CoverPaasMenuEntity> allCoverList) throws XbbException {
        Map<Long, Long> allCoverMap = allCoverList.stream().collect(Collectors.toMap(CoverPaasMenuEntity::getMenuId, CoverPaasMenuEntity::getId));
        List<CoverPaasMenuEntity> insertList = new ArrayList<>();
        List<CoverPaasMenuEntity> updateList = new ArrayList<>();
        //全部算新建
        if (CollectionsUtil.isEmpty(allCoverList)) {
            insertList.addAll(newCoverList);
        } else {
            //判断更新
            newCoverList.forEach(item -> {
                if (Objects.nonNull(allCoverMap.get(item.getMenuId()))) {
                    item.setId(allCoverMap.get(item.getMenuId()));
                    item.setUpdateTime(DateUtil.getNow());
                    updateList.add(item);
                } else {
                    insertList.add(item);
                }
            });
        }
        if (CollectionsUtil.isNotEmpty(insertList)) {
            coverPaasMenuModel.insertBatch(insertList);
        }
        if (CollectionsUtil.isNotEmpty(updateList)) {
            coverPaasMenuModel.updateBatch(updateList, corpid);
        }
        if (CollectionsUtil.isNotEmpty(deleteCoverIds)) {
            coverPaasMenuModel.deleteByMenuIds(deleteCoverIds, corpid);
        }
    }

    @Override
    public MenuQueryVO queryMenuByName(MenuQueryDTO menuQueryDTO) throws XbbException {
        MenuQueryVO menuQueryVO = new MenuQueryVO();
        try {
            Map<String, Object> param = BeanUtil.convertBean2Map(menuQueryDTO, true);
            param.put("orderByStr", "enable DESC, sort ASC, update_time ASC");
            List<Integer> typeIn = new ArrayList<>();
            typeIn.add(MenuTypeEnum.FORM.getType());
            typeIn.add(MenuTypeEnum.PROCESS_FORM.getType());
            param.put("typeIn", typeIn);
            if (menuQueryDTO.getHomeFlag()) {
                // 只有首页才需要搜索已启用的菜单
                param.put("enable", 1);
            }
            param.put(StringConstant.DEL, DelEnum.NORMAL.getDel());
            List<PaasMenuEntity> menuList = paasMenuModel.list(param);
            if (Objects.isNull(menuList)) {
                throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, SystemErrorCodeEnum.API_ERROR_100001.getMsg());
            }
            MenuNewListDTO menuNewListDTO = new MenuNewListDTO();
            List<AppMenuListVO> resultList = new ArrayList<>();
            BeanUtil.copyProperties(menuQueryDTO, menuNewListDTO);
            MenuNewListVO menuNewListVO = new MenuNewListVO();
            boolean searchSelfConfig = true;
            boolean searchCompanyConfig = true;
            List<MenuReturnPojo> commonFormList = getCommonFormList(menuNewListDTO, menuNewListVO, searchSelfConfig, searchCompanyConfig);
            Set<Long> commonFormIdSet = new HashSet<>();
            commonFormList.forEach(item -> {
                commonFormIdSet.add(item.getMenuId());
            });
            List<MenuReturnPojo> quickNewFromList = getQuickNewFormList(menuNewListDTO, menuNewListVO, searchSelfConfig, searchCompanyConfig);
            Set<Long> quickNewFromIdSet = new HashSet<>();
            quickNewFromList.forEach(item -> {
                quickNewFromIdSet.add(item.getMenuId());
            });
            menuList.forEach((item) -> {
                AppMenuListVO appMenuListVO = new AppMenuListVO();
                BeanUtil.copyProperties(item, appMenuListVO);
                if (commonFormIdSet.contains(item.getId())) {
                    appMenuListVO.setCommonFormFlag(1);
                }
                if (quickNewFromIdSet.contains(item.getId())) {
                    appMenuListVO.setQuickNewFormFlag(1);
                }
                resultList.add(appMenuListVO);
            });
            menuQueryVO.setMenuList(resultList);
        } catch (Exception e) {
            LOG.error("queryMenuByName检索应用或者菜单出错", e);
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, SystemErrorCodeEnum.API_ERROR_100001.getMsg());
        }
        return menuQueryVO;
    }

    //==================== private method ====================


    /**
     * 修改应用enable状态，可以将指定应用开启或关闭
     *
     * @param menuChangeStateDTO
     * @throws XbbException 业务异常
     */
    private void changeAppState(MenuChangeStateDTO menuChangeStateDTO) throws XbbException {
        Long appId = menuChangeStateDTO.getAppId();
        String corpid = menuChangeStateDTO.getCorpid();
        Boolean enable = menuChangeStateDTO.getEnable();
        Long appModuleId = menuChangeStateDTO.getAppModuleId();
        String alias = menuChangeStateDTO.getAlias();
        // 需要处理的配置
        List<String> configEnums = Arrays.asList(CompanyConfigEnum.ELECTRONIC_FACE_SHEET.getAlias(), CompanyConfigEnum.LOGISTICS_TRACKING.getAlias(), CompanyConfigEnum.PRICE_MANAGE.getAlias());
        if (Objects.nonNull(alias) && configEnums.contains(alias)) {
            // 公司配置项单独处理
            handleCompanyConfig(menuChangeStateDTO);
            return;
        }
        if (Objects.equals(CompanyConfigEnum.BUSINESS_SEARCH.getAlias(), alias)) {
            // 工商查询单独处理
            handleBusinessSearch(menuChangeStateDTO);
            return;
        }
        PaasAppEntity appEntity = paasAppModel.getByKey(appId, corpid);
        if (appEntity == null) {
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, MessageConstant.APP_NOT_EXIST);
        }
        if (Objects.nonNull(appModuleId)) {
            // 模板中心中的开启和关闭
            AppModuleEntity appModuleEntity = appModuleModel.getByKey(appModuleId);
            if (Objects.isNull(appModuleEntity)) {
                throw new XbbException(TemplateCenterErrorCodeEnum.API_ERROR_402005, TemplateCenterErrorCodeEnum.API_ERROR_402005.getMsg());
            }
            if (Objects.equals(appModuleEntity.getShelves(), 0)) {
                throw new XbbException(TemplateCenterErrorCodeEnum.API_ERROR_402006, TemplateCenterErrorCodeEnum.API_ERROR_402006.getMsg());
            }
        }

        Integer enableInt = enable ? 1 : 0;
        appEntity.setEnable(enableInt);

        try {
            // CRM 不能关闭
            if (!enable && XbbRefTypeEnum.CRM.getAlias().equals(appEntity.getAlias())) {
                throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, MessageConstant.APP_NOT_ALLOW_ENABLE, appEntity.getName());
            }
            // 客户管理不允许关闭
            if (!enable && XbbRefTypeEnum.CUSTOMER_MANAGEMENT.getAlias().equals(appEntity.getAlias())) {
                throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, MessageConstant.APP_NOT_ALLOW_ENABLE, appEntity.getName());
            }
            // 关闭产品应用时，
            if (!enable && XbbRefTypeEnum.PRODUCT.getAlias().equals(appEntity.getAlias())) {
                boolean mirrorFlag = isCompanyMirror(corpid);
                if (mirrorFlag) {
                    // 若使用镜像，进销存开启时不允许关闭(也会存进销存还未启用的情况，所以要判断下null)
                    PaasAppEntity jxcApp = paasAppModel.getByAlias(SystemAppMenuEnum.JXC.getAlias(), corpid);
                    if (Objects.nonNull(jxcApp) && Objects.equals(jxcApp.getEnable(), 1)) {
                        throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, MessageConstant.APP_NOT_ALLOW_ENABLE, appEntity.getName());
                    }
                } else {
                    // 按原逻辑：产品应用不允许关闭
                    throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, MessageConstant.APP_NOT_ALLOW_ENABLE, appEntity.getName());
                }
            }
            // 标准版市场管理不允许开通,如果降套餐的话,展示为开启,但是提示不能开通
            if (enable && XbbRefTypeEnum.MARKET_MANAGEMENT.getAlias().equals(appEntity.getAlias())) {
                boolean standardWithFeeType = marketManagementBusinessHelp.isStandardWithFeeType(corpid);
                if (standardWithFeeType) {
                    throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, MessageConstant.MARKET_MANAGEMENT_NOT_ALLOW_ENABLE, appEntity.getName());
                }
            }
            // 经销商关闭或开启时的校验
            if (XbbRefTypeEnum.DISTRIBUTOR.getAlias().equals(appEntity.getAlias())) {
                initDistributorMenuHelp.enableDistributor(enableInt, corpid, enableInt == 1);
            }
            // 客户管理不允许关闭
            if (!enable && XbbRefTypeEnum.MARKETING_MANAGEMENT.getAlias().equals(appEntity.getAlias())) {
                initDistributorMenuHelp.offLineActivity(corpid);
            }
            if (XbbRefTypeEnum.MARKET_MANAGEMENT.getAlias().equals(appEntity.getAlias())) {
                //启用客户内的关联销售线索字段
                Map<String, Object> param = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
                param.put("corpid", corpid);
                param.put("del", 0);
                param.put("businessType", XbbRefTypeEnum.CUSTOMER_MANAGEMENT.getCode());
                List<PaasFormExplainEntity> paasFormExplainList = paasFormExplainModel.findEntitys(param);
                List<PaasFormExplainEntity> updatePaasFormExplainList = new ArrayList<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);

                if (CollectionsUtil.isNotEmpty(paasFormExplainList)) {
                    for (PaasFormExplainEntity paasFormExplainEntity : paasFormExplainList) {
                        List<FieldAttrEntity> explainList = JSONArray.parseArray(paasFormExplainEntity.getExplains(), FieldAttrEntity.class);
                        Boolean isUpdate = false;
                        for (FieldAttrEntity fieldAttrEntity : explainList) {
                            if (Objects.equals(fieldAttrEntity.getAttr(), CustomerManagementEnum.CLUE_ID.getAttr())) {
                                fieldAttrEntity.setIsOpen(enableInt);
                                isUpdate = true;
                                break;
                            }
                        }
                        if (isUpdate) {
                            paasFormExplainEntity.setExplains(JSONObject.toJSONString(explainList));
                            updatePaasFormExplainList.add(paasFormExplainEntity);
                        }
                    }
                }
                if (CollectionsUtil.isNotEmpty(updatePaasFormExplainList)) {
                    paasFormExplainModel.updateBatch(updatePaasFormExplainList, corpid);
                }
            }
            Map<String, Object> param = new HashMap<>(4);
            param.put("corpid", menuChangeStateDTO.getCorpid());
            param.put("del", DelEnum.NORMAL.getDel());
            if (enable) {
                param.put("enable", enableInt);
            }
            param.put("orderByStr", "sort ASC, update_time ASC ");
            List<PaasAppEntity> appList = paasAppModel.findEntitys(param);
            if (Objects.isNull(appList)) {
                throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, MessageConstant.APP_NOT_EXIST);
            }
            PaasAppEntity lastAppEntity = appList.get(appList.size() - 1);
            Integer count = appList.size();
            if (lastAppEntity.getSort() > count) {
                count = lastAppEntity.getSort();
            }
            if (XbbRefTypeEnum.PRODUCT.getAlias().equals(appEntity.getAlias())) {
                PaasMenuEntity paasMenuEntity = paasMenuModel.getByAlias(appEntity.getAlias(), appId, corpid);
                if (Objects.isNull(paasMenuEntity)) {
                    throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, SystemErrorCodeEnum.API_ERROR_100001.getMsg());
                }
                menuChangeStateDTO.setMenuId(paasMenuEntity.getId());
                changeMenuState(menuChangeStateDTO);
            } else if (XbbRefTypeEnum.JXC.getAlias().equals(appEntity.getAlias())) {
                PaasMenuEntity payManagementMenuEntity = paasMenuModel.getByAlias(XbbRefTypeEnum.PAY_MANAGEMENT.getAlias(), null, corpid);
                if (Objects.nonNull(payManagementMenuEntity) && !Objects.equals(enableInt, payManagementMenuEntity.getEnable())) {
                    //开关进销存模块时，应开关付款管理
                    payManagementMenuEntity.setEnable(enableInt);
                    paasMenuModel.update(payManagementMenuEntity);
                }
                PaasMenuEntity purchaseInvoiceMenuEntity = paasMenuModel.getByAlias(XbbRefTypeEnum.PURCHASE_INVOICE.getAlias(), null, corpid);
                if (Objects.nonNull(purchaseInvoiceMenuEntity) && !Objects.equals(enableInt, purchaseInvoiceMenuEntity.getEnable())) {
                    //开关进销存模块时，应开关进项发票
                    purchaseInvoiceMenuEntity.setEnable(enableInt);
                    paasMenuModel.update(purchaseInvoiceMenuEntity);
                }
                //成本改造方案--开启进销存即开启流水，开启进销存模块时，应开关流水配置
                String stockFlowBillAlias = CompanyConfigEnum.ENABLE_STOCK_FLOW_BILL.getAlias();
                CompanyConfigEntity companyConfigEntity = companyConfigModel.getByConfigAlias(stockFlowBillAlias, corpid);
                CompanyConfigEnum configEnum = CompanyConfigEnum.getByAlias(stockFlowBillAlias);
                if (companyConfigEntity == null) {
                    companyConfigEntity = new CompanyConfigEntity(corpid, configEnum.getName(), stockFlowBillAlias, String.valueOf(enableInt));
                    companyConfigModel.insert(companyConfigEntity);
                } else {
                    companyConfigEntity.setConfigValue(String.valueOf(enableInt));
                    companyConfigModel.update(companyConfigEntity);
                }
                //如果没有库存流水菜单生成库存流水菜单
                PaasMenuEntity paasMenuEntity = paasMenuModel.getByAlias(XbbRefTypeEnum.STOCK_FLOW_BILL.getAlias(), corpid);
                if (Objects.isNull(paasMenuEntity)) {
                    AccordConfigMenuPojo accordConfigMenuPojo = new AccordConfigMenuPojo();
                    accordConfigMenuPojo.setCorpid(corpid);
                    accordConfigMenuPojo.setConfigEntity(companyConfigEntity);
                    accordConfigMenuPojo.setConfigValue(BasicConstant.IS_USE.toString());
                    accordConfigMenuPojo.setConfigEnum(configEnum);
                    accordConfigMenuPojo.setPlatform(PlatFormEnum.WEB.getValue());
                    accordConfigMenuPojo.setUserId(menuChangeStateDTO.getUserId());
                    stockFlowBillService.addMenu(accordConfigMenuPojo);
                }
            }
            // 关闭时，智能助手的相关设置也要关闭
            if (!enable) {
                smartSettingsService.batchDisable(corpid, menuChangeStateDTO.getUserId(), menuChangeStateDTO.getLoginUserName(), menuChangeStateDTO.getHttpHeader(), appEntity, null);
            }
            // 开启进销存时关联开启产品
            if (enable && XbbRefTypeEnum.JXC.getAlias().equals(appEntity.getAlias())) {
                initJxcMenuHelp.setProductByMirror(corpid);
            }

            // 校验呼叫中心和度言
            validateCallCenter(corpid, appEntity.getAlias());
            appEntity.setSort(count + 1);
            paasAppModel.update(appEntity);
            //应用是市场管理的话，刷新缓存
            String marketManagementAlias = SystemAppMenuEnum.MARKET_MANAGEMENT.getAlias();
            if (Objects.equals(appEntity.getAlias(), marketManagementAlias)) {
                paasAppService.setEnable2RedisByAlias(corpid, marketManagementAlias, appEntity.getEnable());
            }
            String userId = menuChangeStateDTO.getUserId();
            String userName = menuChangeStateDTO.getLoginUserName();
            // 记录日志
            String memo;
            OperateTypeEnum operateType;
            if (enable) {
                memo = String.format(I18nMessageUtil.getMessage(LogMemoConstant.LOG_MEMO_USER_UPDATE_APP_ENABLE), userName, appEntity.getName());
                operateType = OperateTypeEnum.ENABLE;
            } else {
                memo = String.format(I18nMessageUtil.getMessage(LogMemoConstant.LOG_MEMO_USER_UPDATE_APP_CLOSE), userName, appEntity.getName());
                operateType = OperateTypeEnum.CLOSE;
            }
            mongoLogHelp.buildLog(corpid, userId, userName, OperateModuleTypeEnum.PAAS_APP, operateType, appEntity.getId().toString(), appEntity.getName(), memo, menuChangeStateDTO.getHttpHeader());
        } catch (XbbException e) {
            throw e;
        } catch (Exception e) {
            LOG.error("changeAppState数据库操作出错", e);
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, SystemErrorCodeEnum.API_ERROR_100001.getMsg());
        }
    }

    @Override
    public void validateCallCenter(String corpid, String alias) throws XbbException {
        paasAppModel.validateCallCenter(corpid, alias);
    }

    @Override
    public boolean enableMenu(String corpid, String alias) throws XbbException {
        return paasMenuModel.enableMenu(corpid, alias);
    }

    /**
     * 修改菜单enable状态，可以将指定菜单开启或关闭
     *
     * @param menuChangeStateDTO
     * @throws XbbException 业务异常
     */
    private void changeMenuState(MenuChangeStateDTO menuChangeStateDTO) throws XbbException {
        Long menuId = menuChangeStateDTO.getMenuId();
        Long appId = menuChangeStateDTO.getAppId();
        String corpid = menuChangeStateDTO.getCorpid();
        Boolean enable = menuChangeStateDTO.getEnable();
        PaasMenuEntity menuEntity = paasMenuModel.getByKey(menuId, corpid);
        // menuEntity 不存在 或 传过来的appId与menu对应的appId不一致
        if (menuEntity == null || !menuEntity.getAppId().equals(appId)) {
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, MessageConstant.MENU_NOT_EXIST);
        }

        // 客户管理不允许关闭
        if (!enable && XbbRefTypeEnum.CUSTOMER_MANAGEMENT.getAlias().equals(menuEntity.getAlias())) {
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, MessageConstant.APP_NOT_ALLOW_ENABLE, menuEntity.getName());
        }
//        // 序列号查询未开启公司级配置不允许开启
//        if (enable && XbbRefTypeEnum.SEQ_SEARCH.getAlias().equals(menuEntity.getAlias()) && !companyConfigService.getSeqManagement(corpid)) {
//            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, MessageConstant.MENU_NOT_ALLOW_ENABLE_BY_OTHER, I18nMessageUtil.getMessage(menuEntity.getName()), I18nMessageUtil.getMessage(CompanyConfigEnum.ENABLE_SEQ_MANAGEMENT.getName()));
//        }
//        // 批次保质期开关和流水开关未开启公司级配置不允许开启
//        if (enable && XbbRefTypeEnum.BATCH_FLOW_BILL.getAlias().equals(menuEntity.getAlias()) && (!companyConfigService.getBatchShelf(corpid) || !companyConfigService.getFlowBook(corpid))) {
//            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, MessageConstant.MENU_NOT_ALLOW_ENABLE_BY_OTHER_AND_OTHER, I18nMessageUtil.getMessage(menuEntity.getName()), I18nMessageUtil.getMessage(CompanyConfigEnum.ENABLE_BATCH_SHELF_MANAGEMENT.getName()), I18nMessageUtil.getMessage(CompanyConfigEnum.ENABLE_STOCK_FLOW_BILL.getName()));
//        }
        // 关闭产品菜单时，
        if (!enable && XbbRefTypeEnum.PRODUCT.getAlias().equals(menuEntity.getAlias())) {
            boolean mirrorFlag = isCompanyMirror(corpid);
            if (mirrorFlag) {
                // 若使用镜像，进销存开启时不允许关闭
                PaasAppEntity jxcApp = paasAppModel.getByAlias(SystemAppMenuEnum.JXC.getAlias(), corpid);
                if (Objects.nonNull(jxcApp) && Objects.equals(jxcApp.getEnable(), 1)) {
                    throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, MessageConstant.APP_NOT_ALLOW_ENABLE, menuEntity.getName());
                }
            } else {
                // 按原逻辑：产品管理不允许关闭
                throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, MessageConstant.APP_NOT_ALLOW_ENABLE, menuEntity.getName());
            }
        }
        // 开启菜单时，开启相应的表单
        if (enable && Objects.equals(menuEntity.getSaasMark(), SaasMarkEnum.SAAS.getCode())) {
            // 若使用镜像，开启菜单时关联开启菜单下的表单和表单解释
            boolean mirrorFlag = isCompanyMirror(corpid);
            if (mirrorFlag) {
                // 注意菜单下有多个表单的情况，例:工作报告，付款管理
                Map<String, Object> param = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
                param.put("corpid", corpid);
                param.put("menuId", menuEntity.getId());
                param.put("del", 0);
                List<PaasFormEntityExt> paasFormList = paasFormModel.findEntitys(param);
                if (!paasFormList.isEmpty()) {
                    paasFormList.forEach(formEntity -> {
                        if (Objects.equals(formEntity.getEnable(), 0)) {
                            formEntity.setEnable(BasicConstant.IS_USE);
                            paasFormModel.update(formEntity);
                            paasFormExplainModel.updateByFormId(formEntity.getId(), corpid, 1);
                        }
                    });
                }
                // 开启报价单的时候，判断产品应用和产品菜单是否已经开启
                if (Objects.equals(menuEntity.getAlias(), XbbRefTypeEnum.QUOTATION.getAlias())) {
                    // 因为产品的应用、菜单等都是关联的，只判断一个就好了
                    PaasAppEntity productApp = paasAppModel.getByAlias(SystemAppMenuEnum.PRODUCT.getAlias(), corpid);
                    if (Objects.isNull(productApp) || Objects.equals(productApp.getEnable(), 0)) {
                        throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, MessageConstant.MENU_NOT_ALLOW_ENABLE_BY_OTHER, menuEntity.getName(), SystemAppMenuEnum.PRODUCT.getName());
                    }
                }
            }
        }
        Integer enableInt = enable ? 1 : 0;
        menuEntity.setEnable(enableInt);
        try {
            Map<String, Object> param = BeanUtil.convertBean2Map(menuChangeStateDTO, true);
            if (enable) {
                param.put("enable", enableInt);
            }
            param.put("appId", appId);
            Integer count = paasMenuModel.getEntitysCount(param);
            if (Objects.isNull(count)) {
                throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, SystemErrorCodeEnum.API_ERROR_100001.getMsg());
            }
            menuEntity.setSort(count + 1);
            paasMenuModel.update(menuEntity);

            // 关闭时，智能助手的相关设置也要关闭
            if (!enable) {
                smartSettingsService.batchDisable(corpid, menuChangeStateDTO.getUserId(), menuChangeStateDTO.getLoginUserName(), menuChangeStateDTO.getHttpHeader(), null, menuEntity);
            }
            boolean saasClose = !enable && Objects.equals(menuEntity.getSaasMark(), SaasMarkEnum.SAAS.getCode());
            if (saasClose) {
                //回（付）款单关闭，则把预收（付）款的菜单也关闭
                if (Objects.equals(menuEntity.getAlias(), XbbRefTypeEnum.PAYMENT_SHEET.getAlias())) {
                    PaasMenuEntity prepaymentMenu = paasMenuModel.getByAlias(XbbRefTypeEnum.PREPAYMENT_BALANCE.getAlias(), corpid);
                    //true预收款开启
                    boolean preFlag = prepaymentMenu != null && Objects.equals(prepaymentMenu.getEnable(), BasicConstant.ONE);
                    if (preFlag) {
                        prepaymentMenu.setEnable(enableInt);
                        paasMenuModel.update(prepaymentMenu);
                    }
                } else if (Objects.equals(menuEntity.getAlias(), XbbRefTypeEnum.PAY_SHEET.getAlias())) {
                    PaasMenuEntity prepaymentMenu = paasMenuModel.getByAlias(XbbRefTypeEnum.PREPAY_BALANCE.getAlias(), corpid);
                    //true预付款开启
                    boolean preFlag = prepaymentMenu != null && Objects.equals(prepaymentMenu.getEnable(), BasicConstant.ONE);
                    if (preFlag) {
                        prepaymentMenu.setEnable(enableInt);
                        paasMenuModel.update(prepaymentMenu);
                    }
                }
            }
            // 记录日志
            String userName = menuChangeStateDTO.getLoginUserName();
            String memo;
            OperateTypeEnum operateType;
            if (enable) {
                memo = String.format(I18nMessageUtil.getMessage(LogMemoConstant.LOG_MEMO_USER_UPDATE_MENU_ENABLE), userName, menuEntity.getName());
                operateType = OperateTypeEnum.ENABLE;
            } else {
                memo = String.format(I18nMessageUtil.getMessage(LogMemoConstant.LOG_MEMO_USER_UPDATE_MENU_CLOSE), userName, menuEntity.getName());
                operateType = OperateTypeEnum.CLOSE;
            }
            mongoLogHelp.buildLog(corpid, menuChangeStateDTO.getUserId(), userName, OperateModuleTypeEnum.PAAS_MENU, operateType, menuEntity.getId().toString(), menuEntity.getName(), memo, menuChangeStateDTO.getHttpHeader());
        } catch (Exception e) {
            LOG.error("changeAppState数据库操作出错", e);
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, SystemErrorCodeEnum.API_ERROR_100001.getMsg());
        }
    }

    /**
     * 公司是否使用镜像
     *
     * @param corpid
     * @author xingxing.xiao
     * @date 2019/12/11 11:20
     */
    private boolean isCompanyMirror(String corpid) {
        Map<String, Object> param = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        param.clear();
        param.put("corpid", corpid);
        param.put("del", 0);
        Integer mirrorCount = mirrorCompanyModel.getEntitysCount(param);
        return mirrorCount > 0;
    }

    @Override
    public List<MenuReturnPojo> getCommonFormList(MenuNewListDTO menuNewListDTO, MenuNewListVO menuNewListVO,
                                                  boolean searchSelfConfig, boolean searchCompanyConfig) throws XbbException {
        Set<Long> commonFormIdSet = new HashSet<>();
        List<MenuReturnPojo> commonFormConfigList = new ArrayList<>();
        try {
            // 常用表单获取逻辑
            String corpid = menuNewListDTO.getCorpid();
            String userId = menuNewListDTO.getUserId();
            String configAlias = UserConfigEnum.COMMON_FORM.getAlias();
            // 管理中心则不需要查用户的配置
            if (searchSelfConfig) {
                UserConfigEntity commonFormConfig = userConfigModel.getByUserId(userId, corpid, configAlias);
                if (Objects.nonNull(commonFormConfig)) {
                    commonFormConfigList = JSONObject.parseArray(commonFormConfig.getConfigValue(), MenuReturnPojo.class);
                    if (!Objects.equals(menuNewListDTO.getPlatform(), PlatFormEnum.WEB.getValue())) {
                        PaasMenuEntity paasMenuEntity = paasMenuModel.getByAlias(ContractCompareMenuEnum.CONTRACT_COMPARE_RESULT.getAlias(), corpid);
                        if (Objects.nonNull(paasMenuEntity) && Objects.nonNull(commonFormConfigList)) {
                            commonFormConfigList.removeIf(item -> item.getMenuId().equals(paasMenuEntity.getId()));
                        }
                    }
                    menuNewListVO.setUserConfigId(commonFormConfig.getId());
                }
            }
            // 用户的常用表单为空时，则获取公司的常用表单
            boolean result = searchCompanyConfig && (Objects.isNull(commonFormConfigList) || commonFormConfigList.isEmpty());
            if (result) {
                configAlias = UserConfigEnum.COMMON_FORM.getAlias();
                CompanyConfigEntity companyConfigEntity = companyConfigModel.getByConfigAlias(configAlias, corpid);
                if (Objects.nonNull(companyConfigEntity)) {
                    commonFormConfigList = JSONObject.parseArray(companyConfigEntity.getConfigValue(), MenuReturnPojo.class);
                    if (!Objects.equals(menuNewListDTO.getPlatform(), PlatFormEnum.WEB.getValue())) {
                        PaasMenuEntity paasMenuEntity = paasMenuModel.getByAlias(ContractCompareMenuEnum.CONTRACT_COMPARE_RESULT.getAlias(), corpid);
                        if (Objects.nonNull(paasMenuEntity) && Objects.nonNull(commonFormConfigList)) {
                            commonFormConfigList.removeIf(item -> item.getMenuId().equals(paasMenuEntity.getId()));
                        }
                    }
                }
            }
            if (Objects.nonNull(commonFormConfigList) && !commonFormConfigList.isEmpty()) {
                commonFormConfigList.forEach((item) -> {
                    commonFormIdSet.add(item.getMenuId());
                });
                menuNewListVO.setCommonFormList(new ArrayList<>(commonFormIdSet));
            }
        } catch (Exception e) {
            LOG.error("menuService.getCommonFormList获取常用表单出错", e);
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, SystemErrorCodeEnum.API_ERROR_100001.getMsg());
        }
        return commonFormConfigList;
    }

    @Override
    public List<MenuReturnPojo> getQuickNewFormList(MenuNewListDTO menuNewListDTO, MenuNewListVO menuNewListVO,
                                                    boolean searchSelfConfig, boolean searchCompanyConfig) throws XbbException {
        List<MenuReturnPojo> quickNewFormList = new ArrayList<>();
        Set<Long> quickNewFormIdSet = new HashSet<>();
        try {
            // 常用表单获取逻辑
            String corpid = menuNewListDTO.getCorpid();
            String userId = menuNewListDTO.getUserId();
            String configAlias = UserConfigEnum.QUICK_NEW_FORM.getAlias() + "_" + menuNewListDTO.getPlatform();

            // 管理中心则不需要查用户的配置
            if (searchSelfConfig) {
                UserConfigEntity quickNewFormConfig = userConfigModel.getByUserId(userId, corpid, configAlias);
                if (Objects.nonNull(quickNewFormConfig)) {
                    quickNewFormList = JSONObject.parseArray(quickNewFormConfig.getConfigValue(), MenuReturnPojo.class);
                    menuNewListVO.setUserConfigId(quickNewFormConfig.getId());
                }
            }
            boolean result = searchCompanyConfig && (Objects.isNull(quickNewFormList) || quickNewFormList.isEmpty());
            if (result) {
                CompanyConfigEntity companyConfigEntity = companyConfigModel.getByConfigAlias(configAlias, corpid);
                if (Objects.nonNull(companyConfigEntity)) {
                    quickNewFormList = JSONObject.parseArray(companyConfigEntity.getConfigValue(), MenuReturnPojo.class);
                }
            }
            if (Objects.nonNull(quickNewFormList) && !quickNewFormList.isEmpty()) {
                quickNewFormList.forEach((item) -> {
                    quickNewFormIdSet.add(item.getMenuId());
                });
            }
            menuNewListVO.setQuickNewFormList(new ArrayList<>(quickNewFormIdSet));
        } catch (Exception e) {
            LOG.error("menuService.getQuickNewFormList获取常用表单出错", e);
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, SystemErrorCodeEnum.API_ERROR_100001.getMsg());
        }
        return quickNewFormList;
    }

    /**
     * 获取对应条件的总数
     *
     * @param params
     * @return java.lang.Integer
     * @throws XbbException 业务异常
     * @author 吴峰
     * @date 2019/2/28 20:43
     */
    private Integer getCount(Map<String, Object> params) throws XbbException {
        Integer count;
        try {
            count = paasMenuModel.getEntitysCount(params);
            if (count == null) {
                throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, MessageConstant.MENU_NOT_EXIST);
            }
        } catch (Exception e) {
            LOG.error("menuServiceImpl.getCount 获取排序出错", e);
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, SystemErrorCodeEnum.API_ERROR_100001.getMsg());
        }
        return count;
    }


    /**
     * 构建管理中心子菜单，传入子菜单类型，目前支持类型有下面四个
     * 1.表单模板，
     * 2.流程设置
     * 3.消息推送
     * 4.打印模板
     * 会过滤掉不需要展示的菜单
     *
     * @param appList           公司应用列表，包括saas应用和paas应用
     * @param controlCenterMenu 子菜单类型， 使用对应的枚举值，目前需要调用的子菜单有描述中的四个
     * @param filterPaas        是否过滤掉paas 1：过滤掉paas 0：saas和paas都不过滤
     * @return 构建好的管理中心子菜单List<PaasAppMenuVO>
     * @author kaka
     */
    private List<PaasAppMenuVO> getControlCenterSubMenuList(List<PaasAppEntity> appList, ControlCenterMenuEnum controlCenterMenu, Integer filterPaas) {
        String pushUrl;
        String[] blockMenuList = {};
        //判断套餐版本是否是"标准版"或者 “市场管理”应用是关闭的 .用于"市场管理"模块是否展示
        Boolean feeTypeIsStandardOrAppIsClosed = feeTypeIsStandardOrAppIsClosed(appList.get(0).getCorpid());
        switch (controlCenterMenu) {
            case FORM_TEMPLATE:
                pushUrl = AccessLinkEnum.FORM_TEMPLATE.getUrl();
                blockMenuList = new String[]{
                        SystemAppMenuEnum.CALL_CENTER.getAlias(),
                        SystemAppMenuEnum.CALL_CENTER_DU_YAN.getAlias(),
                        SystemAppMenuEnum.GROUP_MESSAGE.getAlias(),
                        SystemAppMenuEnum.WORK_ORDER.getAlias(),
                        SystemAppMenuEnum.SEARCH_CUSTOMER.getAlias(),
                        SystemAppMenuEnum.FINE_CLUE.getAlias(),
                        SystemAppMenuEnum.ESIGN.getAlias(),
                        SystemAppMenuEnum.MARKETING_MANAGEMENT.getAlias(),
                        SystemAppMenuEnum.COOL_APP.getAlias(),
                        SystemAppMenuEnum.CONTRACT_COMPARE.getAlias(),
                        SystemAppMenuEnum.CONTRACT_TEMPLATE_BASE.getAlias()
                };
                break;
            case PROCESS_SETTINGS:
                pushUrl = AccessLinkEnum.PROCESS_SETTINGS.getUrl();
                blockMenuList = new String[]{
                        SystemAppMenuEnum.PRODUCT.getAlias(),
                        SystemAppMenuEnum.CALL_CENTER.getAlias(),
                        SystemAppMenuEnum.CALL_CENTER_DU_YAN.getAlias(),
                        SystemAppMenuEnum.GROUP_MESSAGE.getAlias(),
                        SystemAppMenuEnum.WORK_ORDER.getAlias(),
                        SystemAppMenuEnum.SEARCH_CUSTOMER.getAlias(),
                        SystemAppMenuEnum.FINE_CLUE.getAlias(),
                        SystemAppMenuEnum.ESIGN.getAlias(),
                        SystemAppMenuEnum.MARKETING_MANAGEMENT.getAlias(),
                        SystemAppMenuEnum.COOL_APP.getAlias(),
                        SystemAppMenuEnum.CONTRACT_COMPARE.getAlias()

                };
                break;
            case MESSAGE_PUSH:
                pushUrl = AccessLinkEnum.MESSAGE_PUSH.getUrl();
                blockMenuList = new String[]{
                        SystemAppMenuEnum.PRODUCT.getAlias(),
                        SystemAppMenuEnum.JXC.getAlias(),
                        SystemAppMenuEnum.CALL_CENTER.getAlias(),
                        SystemAppMenuEnum.CALL_CENTER_DU_YAN.getAlias(),
                        SystemAppMenuEnum.GROUP_MESSAGE.getAlias(),
                        SystemAppMenuEnum.SEARCH_CUSTOMER.getAlias(),
                        SystemAppMenuEnum.FINE_CLUE.getAlias(),
                        SystemAppMenuEnum.ESIGN.getAlias(),
                        SystemAppMenuEnum.MARKETING_MANAGEMENT.getAlias(),
                        SystemAppMenuEnum.COOL_APP.getAlias(),
                        SystemAppMenuEnum.CONTRACT_COMPARE.getAlias()
                };
                break;
            case PRINT_TEMPLATE:
                pushUrl = AccessLinkEnum.PRINT_TEMPLATE.getUrl();
                blockMenuList = new String[]{
                        SystemAppMenuEnum.CALL_CENTER.getAlias(),
                        SystemAppMenuEnum.CALL_CENTER_DU_YAN.getAlias(),
                        SystemAppMenuEnum.GROUP_MESSAGE.getAlias(),
                        //开启产品 但只展示自定义数据
//                        SystemAppMenuEnum.PRODUCT.getAlias(),
                        //市场管理模块没有打印
                        // 放开市场管理的应用，但是不支持市场活动和线索的打印 @date 2022/7/29 10:29
//                        SystemAppMenuEnum.MARKET_MANAGEMENT.getAlias(),
                        /**
                         * 资金管理一期改造，需要资金管理的打印设置，所以需要放出
                         * @author chenshan
                         * @Date 2019-11-06 10:06
                        */
//                        SystemAppMenuEnum.FUND_MANAGEMENT.getAlias(),
//                         SystemAppMenuEnum.WORK_ORDER.getAlias(),
                        SystemAppMenuEnum.SEARCH_CUSTOMER.getAlias(),
                        SystemAppMenuEnum.FINE_CLUE.getAlias(),
                        SystemAppMenuEnum.ESIGN.getAlias(),
                        SystemAppMenuEnum.MARKETING_MANAGEMENT.getAlias(),
                        SystemAppMenuEnum.DISTRIBUTOR.getAlias(),
                        SystemAppMenuEnum.COOL_APP.getAlias(),
                        SystemAppMenuEnum.CONTRACT_COMPARE.getAlias()
                };
                break;
            default:
                pushUrl = AccessLinkEnum.FORM_TEMPLATE.getUrl();
        }
        List<PaasAppMenuVO> retList = new ArrayList<>();
        String finalPushUrl = pushUrl;
        List<String> finalBlockMenuList = Arrays.asList(blockMenuList);
        StringBuilder urlStringBuilder = new StringBuilder();
        // 过滤部分模块，paas应用且不在本子菜单禁用列表中的数据可以呈现
        appList.stream().filter(item -> !Objects.equals(filterPaas, 1) || !Objects.equals(SaasMarkEnum.PAAS.getCode(), item.getSaasMark()))
                .filter(item -> SaasMarkEnum.PAAS.getCode().equals(item.getSaasMark()) || !finalBlockMenuList.contains(item.getAlias())) //是paas应用 且么有被禁用
                .filter(item -> ifContainPassForm(item.getCorpid(), item.getId(), item.getAlias(), controlCenterMenu)) //在ControlCenterMenuEnum.PRINT_TEMPLATE ，表单模板菜单下  某些saas应用在只展示自定义表单的情况下，判断是否有自定义表单
                .forEach(item -> {
                    //“标准版”套餐是没有“市场管理”的模块的
                    if (feeTypeIsStandardOrAppIsClosed && SystemAppMenuEnum.MARKET_MANAGEMENT.getAlias().equals(item.getAlias())) {
                        return;
                    }
                    PaasAppMenuVO paasAppMenuVO = new PaasAppMenuVO();
                    BeanUtil.copyProperties(item, paasAppMenuVO);
                    urlStringBuilder.setLength(0); // 清空
                    urlStringBuilder.append(finalPushUrl)
                            .append("?appId=").append(paasAppMenuVO.getId())
                            .append("&saasMark=").append(paasAppMenuVO.getSaasMark())
                            .append("&appName=").append(item.getName());
                    if (Objects.equals(SystemAppMenuEnum.DISTRIBUTOR.getAlias(), item.getAlias()) || Objects.equals(SystemAppMenuEnum.ORDER_CENTER.getAlias(), item.getAlias())) {
                        urlStringBuilder.append("&distributorMark=").append(DistributorMarkEnum.DISTRIBUTOR.getCode());
                        paasAppMenuVO.setDistributorMark(DistributorMarkEnum.DISTRIBUTOR.getCode());
                    }
                    paasAppMenuVO.setUrl(urlStringBuilder.toString());
                    retList.add(paasAppMenuVO);
                });
        return retList;
    }

    /**
     * 查询打印模板下，某个应用下是否有paas表单
     *
     * @param corpid 公司
     * @param appId  应用id
     * @param alias  需要被判断的应用 别名
     * @return 有pass表单的话返回为true 没有的话返回为fale
     */
    boolean ifContainPassForm(String corpid, Long appId, String alias, ControlCenterMenuEnum controlCenterMenu) {

        //如果不是打印模板子菜单
        if (controlCenterMenu != ControlCenterMenuEnum.PRINT_TEMPLATE) {
            return true;
        }

        List<String> filterApps = new ArrayList<>();
        filterApps.add(SystemAppMenuEnum.PRODUCT.getAlias());
        filterApps.add(SystemAppMenuEnum.MARKET_MANAGEMENT.getAlias());

        if (filterApps.contains(alias)) {
            Map<String, Object> params = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
            params.put("corpid", corpid);
            params.put("appId", appId);
            params.put("del", DelEnum.NORMAL.getDel());
            params.put("saasMark", SaasMarkEnum.PAAS.getCode());
            int num = paasFormModel.getEntitysCount(params);
            return num != 0;
        } else {
            return true;
        }

    }

    /**
     * 判断公司套餐是否是 "标准版" 或者 "市场管理"应用是否开启
     *
     * @param corpid
     * @return
     */
    private Boolean feeTypeIsStandardOrAppIsClosed(String corpid) {
        Boolean isStandardWithFeeType = false;
        try {
            isStandardWithFeeType = marketManagementBusinessHelp.feeTypeIsStandardOrAppIsClosed(corpid);
        } catch (Exception e) {
            LOG.error("isStandardWithFeeType 异常{}", e.getMessage());
        }
        return isStandardWithFeeType;
    }

    /**
     * 处理公司配置
     *
     * @param menuChangeStateDTO
     * @throws XbbException
     * @author xinpeng.jiang
     * @date 2021/7/27 16:21
     * @version 1.0
     */
    private void handleCompanyConfig(MenuChangeStateDTO menuChangeStateDTO) throws XbbException {
        String corpid = menuChangeStateDTO.getCorpid();
        Long appId = menuChangeStateDTO.getAppId();
        String alias = menuChangeStateDTO.getAlias();
        Boolean enable = menuChangeStateDTO.getEnable();
        CompanyConfigEnum companyConfigEnum = CompanyConfigEnum.getByAlias(alias);
        if (enable) {
            if (packageHelp.isStandardWithFeeType(corpid)) {
                throw new XbbException(TemplateCenterErrorCodeEnum.API_ERROR_402008);
            }
            // 价格管理还需要增加或更新菜单
            if (Objects.equals(alias, CompanyConfigEnum.PRICE_MANAGE.getAlias())) {
                MenuInitDTO menuInitDTO = new MenuInitDTO();
                BeanUtil.copyProperties(menuChangeStateDTO, menuInitDTO, true);
                menuInitDTO.setAlias(XbbRefTypeEnum.DISTRIBUTOR.getAlias());
                initPriceMenuHelp.initMenu(menuInitDTO, new HashMap<>());
            }
            CompanyConfigEntity companyConfigEntity = companyConfigModel.getByConfigAlias(alias, corpid);
            if (Objects.nonNull(companyConfigEntity)) {
                companyConfigEntity.setConfigValue(BasicConstant.ONE.toString());
                companyConfigModel.update(companyConfigEntity);
            } else {
                companyConfigEntity = new CompanyConfigEntity(corpid, companyConfigEnum.getName(), companyConfigEnum.getAlias(), BasicConstant.IS_USE.toString());
                companyConfigModel.insert(companyConfigEntity);
            }
        } else {
            CompanyConfigEntity companyConfigEntity = companyConfigModel.getByConfigAlias(alias, corpid);
            if (Objects.nonNull(companyConfigEntity)) {
                companyConfigEntity.setConfigValue(BasicConstant.ZERO.toString());
                companyConfigModel.update(companyConfigEntity);
            } else {
                companyConfigEntity = new CompanyConfigEntity(corpid, companyConfigEnum.getName(), companyConfigEnum.getAlias(), BasicConstant.ZERO.toString());
                companyConfigModel.insert(companyConfigEntity);
            }
            if (Objects.equals(alias, CompanyConfigEnum.PRICE_MANAGE.getAlias())) {
                PaasMenuEntity paasMenuEntity = paasMenuModel.getByAlias4Distributor(XbbRefTypeEnum.PRICE_SET_PRODUCT.getAlias(), corpid, DistributorMarkEnum.DISTRIBUTOR.getCode());
                if (Objects.nonNull(paasMenuEntity)) {
                    paasMenuEntity.setEnable(0);
                    paasMenuModel.update(paasMenuEntity);
                }
                priceSetModel.closePriceManage(corpid);
            }
        }
        // 记录日志
        String memo;
        OperateTypeEnum operateType;
        String userId = menuChangeStateDTO.getUserId();
        String userName = menuChangeStateDTO.getLoginUserName();
        if (enable) {
            memo = String.format(I18nMessageUtil.getMessage(LogMemoConstant.LOG_MEMO_USER_UPDATE_APP_ENABLE), userName, companyConfigEnum.getName());
            operateType = OperateTypeEnum.ENABLE;
        } else {
            memo = String.format(I18nMessageUtil.getMessage(LogMemoConstant.LOG_MEMO_USER_UPDATE_APP_CLOSE), userName, companyConfigEnum.getName());
            operateType = OperateTypeEnum.CLOSE;
        }
        mongoLogHelp.buildLog(corpid, userId, userName, OperateModuleTypeEnum.PAAS_APP, operateType, appId.toString(), companyConfigEnum.getName(), memo, menuChangeStateDTO.getHttpHeader());
    }

    /***
     * 处理工商查询的配置
     *
     * @param menuChangeStateDTO 入参
     * @throws
     * @author hongxiao
     * @date 2022-01-10 19:19
     * @since
     * @version
     */
    private void handleBusinessSearch(MenuChangeStateDTO menuChangeStateDTO) throws XbbException {
        String corpid = menuChangeStateDTO.getCorpid();
        Long appId = menuChangeStateDTO.getAppId();
        String alias = menuChangeStateDTO.getAlias();
        Boolean enable = menuChangeStateDTO.getEnable();
        CompanyConfigEnum companyConfigEnum = CompanyConfigEnum.getByAlias(alias);
        CompanyConfigEntity companyConfigEntity = companyConfigModel.getByConfigAlias(alias, corpid);
        if (enable) {
            if (Objects.nonNull(companyConfigEntity)) {
                companyConfigEntity.setConfigValue(BasicConstant.ONE.toString());
            } else {
                companyConfigEntity = new CompanyConfigEntity(corpid, companyConfigEnum.getName(), companyConfigEnum.getAlias(), BasicConstant.IS_USE.toString());
            }
        } else {
            if (Objects.nonNull(companyConfigEntity)) {
                companyConfigEntity.setConfigValue(BasicConstant.ZERO.toString());
            } else {
                companyConfigEntity = new CompanyConfigEntity(corpid, companyConfigEnum.getName(), companyConfigEnum.getAlias(), BasicConstant.ZERO.toString());
            }
        }
        companyConfigModel.save(companyConfigEntity);
        // 记录日志
        String memo;
        OperateTypeEnum operateType;
        String userId = menuChangeStateDTO.getUserId();
        String userName = menuChangeStateDTO.getLoginUserName();
        if (enable) {
            memo = String.format(I18nMessageUtil.getMessage(LogMemoConstant.LOG_MEMO_USER_UPDATE_APP_ENABLE), userName, companyConfigEnum.getName());
            operateType = OperateTypeEnum.ENABLE;
        } else {
            memo = String.format(I18nMessageUtil.getMessage(LogMemoConstant.LOG_MEMO_USER_UPDATE_APP_CLOSE), userName, companyConfigEnum.getName());
            operateType = OperateTypeEnum.CLOSE;
        }
        mongoLogHelp.buildLog(corpid, userId, userName, OperateModuleTypeEnum.PAAS_APP, operateType, appId.toString(), companyConfigEnum.getName(), memo, menuChangeStateDTO.getHttpHeader());
    }

    /**
     * 校验应用中表单和流程表单启用的数量
     *
     * @param corpid
     * @param appId
     * @return 应用中表单和流程表单启用的数量
     * @throws XbbException
     */
    private Integer validateFormMenuLengthInApp(String corpid, Long appId) throws XbbException {
        Map<String, Object> params = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        params.put(StringConstant.CORPID, corpid);
        params.put(StringConstant.DEL, DelEnum.NORMAL.getDel());
        params.put("appId", appId);
        List<Integer> typeIn = new ArrayList<>();
        typeIn.add(MenuTypeEnum.FORM.getType());
        typeIn.add(MenuTypeEnum.PROCESS_FORM.getType());
        params.put("typeIn", typeIn);
        params.put("enable", 1);
        params.put("orderByStr", "sort DESC ");
        Integer count = paasMenuModel.getEntitysCount(params);
        if (count > PaasConstant.FORM_MAX_LENGTH) {
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, MessageConstant.FORM_LENGTH_TOO_MUCH);
        }
        return count;
    }

    private IsActiveAIComboVO isActiveAICombo(String corpid, UserVO loginUser, String platform, Boolean isAdminOrBoss) throws XbbException {
        //判断是否开启套餐
        IsActiveAIComboVO vo = new IsActiveAIComboVO();
        vo.setIsExpired(false);
        XbbResponse<IsActiveAIComboVO> response = new XbbResponse<>(vo);
        try {
            BaseDTO baseDTO = new BaseDTO();
            baseDTO.setCorpid(corpid);
            baseDTO.setUserId(loginUser.getUserId());
            baseDTO.setPlatform(platform);
            String lang = LocaleContextHolder.getLocale().toString();
            response = aiFeignClient.isActiveCombo(baseDTO, lang);
            if (!Objects.equals(response.getCode(), ErrorCodeEnum.API_SUCCESS.getCode())) {
                return vo;
            }
        } catch (Exception e) {
            LOG.info("corpid为{}未开启AI", corpid);
        }
        vo = response.getResult();
        //判断是否有AI权限
        if (!isAdminOrBoss && !loginUser.getPermSet().contains(ProPermissionAliasEnum.AI_CENTER.getAlias())) {
            vo.setIsExpired(false);
        }
        return vo;
    }

    private ControlCenterMenuVO getAICenterMenuList(String platform) {
        ControlCenterMenuVO menuVO = new ControlCenterMenuVO();
        AICenterMenuEnum aiCenterMenuEnum = AICenterMenuEnum.getParent();
        menuVO.setName(aiCenterMenuEnum.getName());
        menuVO.setIcon(aiCenterMenuEnum.getIcon());
        menuVO.setAlias(aiCenterMenuEnum.getAlias());
        List<PaasAppMenuVO> subMenuList = new ArrayList<>();
        menuVO.setSubMenuList(subMenuList);
        List<AICenterMenuEnum> aiCenterMenuEnumList = AICenterMenuEnum.getChildList();
        for (AICenterMenuEnum item : aiCenterMenuEnumList) {
            if (!item.getPlatform().equals(platform) && !item.getPlatform().equals(PlatFormEnum.WEB.getValue())) {
                continue;
            }
            PaasAppMenuVO child = new PaasAppMenuVO();
            child.setName(item.getName());
            child.setAlias(item.getAlias());
            child.setIcon(item.getIcon());
            child.setColor(item.getColor());
            child.setType(BasicConstant.ZERO);
            String url = proBaseConfig.getAiCenterChartUrl();
            Map<String, Object> valueMap = new HashMap<>();
            valueMap.put("mobileLinkAppId", url + item.getMobileUrl());
            valueMap.put("pcLinkAppId", url + item.getUrl());
            Map<String, Object> actionsMap = new HashMap<>();
            actionsMap.put("value", valueMap);
            actionsMap.put("type", "openMenuQianKun");
            Map<String, Object> map = new HashMap<>();
            map.put("actions", actionsMap);
            map.put("pcActions", new ArrayList<>());
            map.put("mobileActions", new ArrayList<>());
            Map<String, Object> keyMap = new HashMap<>();
            keyMap.put("key", "value");
            map.put("diy_params", keyMap);
            String actions = JSONObject.toJSONString(map);
            child.setActions(actions);
            menuVO.getSubMenuList().add(child);
        }
        return menuVO;
    }
}
